在WebAPI操作方法中抛出HttpResponseException返回空200响应

jcv*_*dan 6 .net c# asp.net-web-api

我正在尝试从我的应用程序返回适当的Http代码和响应,但我正在努力.似乎有两种方法可以返回特定的http响应.

我想要处理它的方式是扔一个HttpResponseException:

public Information Get(int apiKey)
{
    if (!_users.Authenticate(apiKey))
    {
        var response = new HttpResponseMessage();
        response.StatusCode = (HttpStatusCode)401;
        response.ReasonPhrase = "ApiKey invalid";

        throw new HttpResponseException(response);
    }

    return _info.Get();
}
Run Code Online (Sandbox Code Playgroud)

但是,当我这样做时,我看到的响应只是一个空的200响应!

您似乎也可以更改操作方法的签名以返回HttpResponseMessage如下所示:

public HttpResponseMessage Get()
{
    if (!_users.Authenticate(apiKey))
    {
        return Request.CreateResponse((HttpStatusCode) 401, "ApiKey invalid");
    }

    return Request.CreateResponse((HttpStatusCode) 200, _info.Get());
}
Run Code Online (Sandbox Code Playgroud)

我真的不想这样做,如果我可以帮助它,我宁愿把我的返回类型作为我试图检索的对象而不是每次都包装它HttpResponseMessage.

有没有理由为什么第一个方法返回一个空的200而不是401我想要它的消息?

Mar*_*ers 5

两种可能的方案;

首先.确保将IIS配置为允许错误通过

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

第二.我不完全确定,但ASP.NET Web API 可能要求您开发自定义ActionFilter以正确地将异常转换为结果类型.这是我个人在Web API中进行错误处理的方式:

  1. 允许在Web API中抛出任何类型的异常,就像在任何其他.NET应用程序中一样
  2. 编写一个自定义ActionFilter来捕获异常并将它们转换为适当的格式.例如,我以自定义JSON格式序列化所有异常.在客户端,我有一些自定义的AJAX技巧,可以根据这种格式处理错误(例如验证异常).