我正在尝试测试一些错误响应(BadRequest,未授权,...)使用Refit等,我实现了一个返回任何所需响应的TestHandler。使用"OK“(HTTP状态代码200)响应时,响应可以正常工作:
public class Program
{
private static async Task Main()
{
var api = RestService.For<ITest>(
new HttpClient(new TestHandler(HttpStatusCode.OK))
{
BaseAddress = new Uri("https://example.com")
}
);
Console.WriteLine(await api.Test("foo").ConfigureAwait(false));
}
}
public interface ITest
{
[Get("/foo/{bar}")]
Task<string> Test(string bar);
}
public class TestHandler : HttpMessageHandler
{
private readonly HttpResponseMessage _response;
public TestHandler(HttpStatusCode httpStatusCode)
=> _response = new HttpResponseMessage(httpStatusCode) { Content = new StringContent("Yay!") };
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> Task.FromResult(_response);
}但是,每当我将响应状态代码更改为(例如) BadRequest (400)、NotFound (404)或未授权(401) Refit时,都会抛出NullReferenceException
Object reference not set to an instance of an object.
at Refit.DefaultApiExceptionFactory.<CreateExceptionAsync>d__4.MoveNext() in /_/Refit/RefitSettings.cs:line 183
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Refit.RequestBuilderImplementation.<>c__DisplayClass14_0`2.<<BuildCancellableTaskFuncForMethod>b__0>d.MoveNext() in /_/Refit/RequestBuilderImplementation.cs:line 313
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at RefitTest.Program.<Main>d__0.MoveNext() in C:\Users\Rob\Source\Repos\RefitTest\RefitTest\Program.cs:line 18这指向RefitSettings.cs line 183。但我不明白为什么200OK可以工作,而其他任何响应都不行?我做错了什么?
编辑:为了进一步调试,我克隆了Refit,并用Refit NuGet包替换了对Refit项目的项目引用。这会产生一个InvalidOperationException: ITest doesn't look like a Refit interface. Make sure it has at least one method with a Refit HTTP method attribute and Refit is installed in the project。此外,返回几个版本(我已经转到5.2.4)也没有帮助。
发布于 2021-09-22 12:44:10
在同事的帮助下找到了!事实证明HttpResponseMessage需要一些/任何RequestMessage。
变化
public TestHandler(HttpStatusCode httpStatusCode)
=> _response = new HttpResponseMessage(httpStatusCode)
{
Content = new StringContent("Yay!")
};至:
public TestHandler(HttpStatusCode httpStatusCode)
=> _response = new HttpResponseMessage(httpStatusCode)
{
RequestMessage = new(), // <-- This one here...
Content = new StringContent("Yay!")
};它的工作方式和预期的一样。正如问题(和评论)中所说,我很接近,但显然是半睡半醒,因为这正是它指向我的地方。
我已经提交了一个问题here。
https://stackoverflow.com/questions/69266814
复制相似问题