如何从WebAPI向AngularJS返回状态401,并包含自定义消息

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

本文关键字:包含 自定义消息 状态 返回 WebAPI AngularJS      更新时间:2023-09-26

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

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

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

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

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

我需要能够做到这两件事:从服务器返回自定义消息,并将返回的状态代码设置为我想要的任何代码,在本例中为401。

有人知道如何做到这一点吗?

[编辑]解决方案:

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

试着像这样返回HttpResponseMessage

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

这应该会生成这样的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"}

我使用了一个响应拦截器。响应拦截器相当于一个"过滤器",所有响应都通过它,我可以询问状态代码并执行逻辑。

类似这样的东西:

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');
});

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