加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在WebAPI操作方法中抛出HttpResponseException,返回空200

发布时间:2020-12-15 08:40:08 所属栏目:百科 来源:网络整理
导读:我正在尝试从我的应用程序返回适当的Http代码和响应,但我正在努力.似乎有两种方法可以返回特定的http响应. 我想要处理的方法是抛出一个HttpResponseException: public Information Get(int apiKey){ if (!_users.Authenticate(apiKey)) { var response = ne
我正在尝试从我的应用程序返回适当的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();
}

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

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

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

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

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

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

解决方法

两种可能的方案;

第一. Make sure your IIS is configured to let errors pass through

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

第二.我不完全确定,但ASP.NET Web API may require you to develop a custom ActionFilter to properly translate Exceptions to result types.这是我个人在Web API中进行错误处理的方式:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读