如何从的WebAPI返回状态401 AngularJS,还包括一个自定义消息? [英] How do you return status 401 from WebAPI to AngularJS and also include a custom message?
问题描述
在我的WebAPI类,一个 ApiController
,我拨打电话,如:
字符串myCustomMessage = .....;抛出新的Htt presponseException(
新的Htt presponseMessage(的HTTPStatus code.Unauthorized)
{ReasonPhrase = myCustomMessage});
当我打电话使用AngularJS $资源
服务,我得到401状态字段的响应,在承诺的catch块。 401场比赛的HTTPStatus code.Unauthorized
,所以一切正常。
的问题,但是,是响应的数据字段为空(NULL)。我不明白的myCustomMessage回来了。
现在,如果而不是抛出一个的Htt presponseException
例外,我只是抛出一个普通的例外
与一条消息,该消息确实使摇摆回角。
我需要能够做两件事:从服务器返回一个自定义消息,以及已经返回的状态code是我想做的事情,在这种情况下,401
。任何人知道如何使这项工作?
解决方案:
抛出新的Htt presponseException(
Request.CreateErrorResponse(的HTTPStatus code.Unauthorized,myCustomMessage));
请返回的Htt presponseMessage
是这样的。
公开的Htt presponseMessage的get()
{
返回Request.CreateErrorResponse(
的HTTPStatus code.Unauthorized,您没有权限);
}
这应该产生一个HTTP响应消息是这样的。
HTTP / 1.1 401未经授权
内容类型:应用程序/ JSON的;字符集= UTF-8
服务器:Microsoft-IIS / 8.0
日期:星期六,2014年4月12日7时12分五十四秒GMT
内容长度:36{消息:您没有权限}
In my WebAPI class, an ApiController
, I make a call such as:
string myCustomMessage = .....;
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.Unauthorized)
{ ReasonPhrase = myCustomMessage });
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.
The problem, however, is that the data field of the response is empty (null). I don't get the myCustomMessage returned.
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.
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.
Anyone know how to make that work?
[edit] Solution:
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Unauthorized, myCustomMessage));
Try returning HttpResponseMessage
like this.
public HttpResponseMessage Get()
{
return Request.CreateErrorResponse(
HttpStatusCode.Unauthorized, "You are not authorized");
}
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"}
这篇关于如何从的WebAPI返回状态401 AngularJS,还包括一个自定义消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!