投掷的Htt presponseException中的WebAPI操作方法返回空200响应 [英] Throwing HttpResponseException in WebAPI action method returning empty 200 response

查看:231
本文介绍了投掷的Htt presponseException中的WebAPI操作方法返回空200响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图返回相应的HTTP codeS和响应从我的应用程序,但我在努力。看来,有两种方法可以返回特定的HTTP响应。

I'm trying to return appropriate Http codes and responses from my application but I am struggling. It seems that there are 2 ways to return specific http responses.

我要处理这个问题的方法是通过抛出的Htt presponseException

The way I want to deal with it is by throwing a 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();
}

不过,当我做到这一点,我看到的反应只是一个空200响应!

However, when I do this the response I see is just an empty 200 response!

这也看来你也可以改变你的操作方法返回一个的Htt presponseMessage 这样的签名:

It also seems that you can also change the signature of your action method to return a HttpResponseMessage like this:

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

    return Request.CreateResponse((HttpStatusCode) 200, _info.Get());
}

我真的不想这样做,如果我能帮助它,我宁愿有我的返回类型,因为我试图检索,而不是在每一次包裹它的对象的Htt presponseMessage

还有一个原因,为什么第一种方法返回一个空的200,而不是401,因为我想要的信息?

Is there a reason why the first method is returning an empty 200 rather than the 401 with the message as I want it to?

推荐答案

两种可能的解决方案;

Two possible solutions;

第一确保您的IIS配置为允许误差通过通过

<configuration>
  <system.webServer>
    <httpErrors existingResponse="PassThrough" />
  </system.webServer>
</configuration>

。我不能完全肯定,但的ASP.NET Web API 可能需要你开发一个自定义ActionFilter正确翻译例外的结果类型。这是这样,我亲手做的错误处理的Web API:

Second. I am not entirely sure, but ASP.NET Web API may require you to develop a custom ActionFilter to properly translate Exceptions to result types. This is the way I personally do error handling in Web API:

  1. 允许任何类型的异常的网络API被抛出,就像你会做任何其他的.NET应用程序
  2. 在编写自定义ActionFilter,捕获异常并将其转换为相应的格式。举例来说,我在序列化的自定义JSON格式的所有例外。在客户端,我有一些自定义的AJAX挂羊头卖狗肉,可以在此基础上的格式处理错误(如验证例外)。

这篇关于投掷的Htt presponseException中的WebAPI操作方法返回空200响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆