javascript 如何将状态 401 从 WebAPI 返回到 AngularJS 并包含自定义消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23025884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:11:59  来源:igfitidea点击:

How do you return status 401 from WebAPI to AngularJS and also include a custom message?

javascriptangularjsasp.net-web-api

提问by Daisha Lynn

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

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

string myCustomMessage = .....;

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

When I call using AngularJS $resourceservice, 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.

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

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

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

Now, if rather than throwing a HttpResponseExceptionexception, I just throw a regular Exceptionwith a message, that message does make it sway back to Angular.

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

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.

我需要能够做到这两点:从服务器返回自定义消息,以及返回的状态代码是我想要的,在这种情况下是 401。

Anyone know how to make that work?

有谁知道如何使它工作?

[edit] Solution:

[编辑] 解决方案:

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

采纳答案by Badri

Try returning HttpResponseMessagelike this.

尝试这样返回HttpResponseMessage

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

This should produce an HTTP response message like this.

这应该会产生这样的 HTTP 响应消息。

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"}

回答by Amir Popovich

I use a response interceptor for that. A response interceptor is pretty much a "filter" where all responses pass through and I can ask about there status code and perform logic.

我为此使用了响应拦截器。响应拦截器几乎是一个“过滤器”,所有响应都通过其中,我可以询问那里的状态代码并执行逻辑。

Something like this:

像这样的东西:

myModule.factory('responseInterceptor', function ($q) {
    return {
        response: function (res) {
           switch(res.status){
             case 401:
                     // do what you want
           }
           return res;
        },
        responseError: function (res) {
            return $q.reject(res);
        }
    };
});

myModule.config(function ($httpProvider) {
    $httpProvider.interceptors.push('responseInterceptor');
});

About your custom message, you can add it in a http header. In my case, when I get a 401, I add a location header with a url and redirect to it.

关于您的自定义消息,您可以将其添加到 http 标头中。就我而言,当我收到 401 时,我添加了一个带有 url 的位置标头并重定向到它。