You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试Refit实现的API错误响应时抛出NullReferenceException如何解决

问题根源

你遇到的NullReferenceException是因为自定义TestHandler返回的HttpResponseMessage没有关联对应的请求对象:

  • 你预先创建的_response实例的RequestMessage属性为null
  • 当返回200状态码时,Refit不会走异常生成逻辑,直接解析响应内容返回,因此不会触发空引用
  • 当返回非200状态码时,Refit的默认异常工厂会尝试读取RequestMessage中的请求信息构造ApiException,此时就会抛出空引用异常

修复方法

修改TestHandler,每次请求返回新的响应实例,并关联当前请求对象即可,修改后代码如下:

public class TestHandler : HttpMessageHandler
{
    private readonly HttpStatusCode _httpStatusCode;

    public TestHandler(HttpStatusCode httpStatusCode)
        => _httpStatusCode = httpStatusCode;

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(new HttpResponseMessage(_httpStatusCode) 
        { 
            Content = new StringContent("Yay!"),
            // 必须绑定当前请求,避免异常构造时空引用
            RequestMessage = request
        });
    }
}

修复后你可以通过捕获ApiException获取错误响应的详细信息:

try
{
    Console.WriteLine(await api.Test("foo").ConfigureAwait(false));
}
catch (ApiException ex)
{
    Console.WriteLine($"状态码:{ex.StatusCode},错误内容:{ex.Content}");
}

本地源码引用报错说明

你替换为本地Refit源码引用后出现的ITest doesn't look like a Refit interface报错,是因为Refit依赖源生成器生成接口的代理实现,官方NuGet包会自动引入源生成器,你本地项目引用时需要同时引用Refit主项目和对应的源生成器项目,且确保项目开启了C#源生成器支持即可解决。

内容的提问来源于stack exchange,提问作者RobIII

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:15:05