如何将状态 401 从 WebAPI 返回到 AngularJS 并包含自定义消息? [英] How do you return status 401 from WebAPI to AngularJS and also include a custom message?

查看:21
本文介绍了如何将状态 401 从 WebAPI 返回到 AngularJS 并包含自定义消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 WebAPI 类中,一个 ApiController,我进行了如下调用:

In my WebAPI class, an ApiController, I make a call such as:

string myCustomMessage = .....;

throw new HttpResponseException(
    new HttpResponseMessage(HttpStatusCode.Unauthorized)
        { ReasonPhrase = myCustomMessage });

当我使用 AngularJS $resource 服务调用时,我确实在状态字段中获得了 401 响应,在承诺的 catch 块中.401 匹配 HttpStatusCode.Unauthorized,所以一切正常.

When I call using AngularJS $resource service, I do get 401 in the status field the response, in the catch block of the promise. The 401 matches HttpStatusCode.Unauthorized, so all's well.

然而,问题是响应的数据字段为空(null).我没有得到返回的 myCustomMessage.

The problem, however, is that the data field of the response is empty (null). I don't get the myCustomMessage returned.

现在,如果我不是抛出 HttpResponseException 异常,而是抛出一个带有消息的常规 Exception,那么该消息确实会使其摇摆回 Angular.

Now, if rather than throwing a HttpResponseException exception, I just throw a regular Exception with a message, that message does make it sway back to Angular.

我需要能够做到这两点:从服务器返回自定义消息,以及返回的状态代码是我想要的任何内容,在本例中为 401.

I need to be able to do both: return a custom message from the server, as well as have the returned status code be whatever I want, in this case 401.

有人知道怎么做吗?

解决方案:

 throw new HttpResponseException(
     Request.CreateErrorResponse(HttpStatusCode.Unauthorized, myCustomMessage));

推荐答案

尝试像这样返回 HttpResponseMessage.

public HttpResponseMessage Get()
{
    return Request.CreateErrorResponse(
              HttpStatusCode.Unauthorized, "You are not authorized");
}

这应该会产生一个像这样的 HTTP 响应消息.

This should produce an HTTP response message like this.

HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/8.0
Date: Sat, 12 Apr 2014 07:12:54 GMT
Content-Length: 36

{"Message":"You are not authorized"}

这篇关于如何将状态 401 从 WebAPI 返回到 AngularJS 并包含自定义消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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