Javascript 如何将状态401从WebAPI返回给AngularJS并包含自定义消息?
在我的WebAPI类中,一个Javascript 如何将状态401从WebAPI返回给AngularJS并包含自定义消息?,javascript,angularjs,asp.net-web-api,Javascript,Angularjs,Asp.net Web Api,在我的WebAPI类中,一个ApiController,我进行如下调用: string myCustomMessage = .....; throw new HttpResponseException( new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = myCustomMessage }); 当我使用AngularJS$resource服务调用时,我在promise的catch块
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
,那么该消息确实会使它返回角度
我需要能够同时执行这两项操作:从服务器返回自定义消息,以及让返回的状态代码为我想要的任何代码,在本例中为401
有人知道怎么做吗
[编辑]
解决方案:
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.Unauthorized, myCustomMessage));
我使用了一个响应拦截器。 响应拦截器基本上是一个“过滤器”,所有响应都会通过它,我可以询问它们的状态代码并执行逻辑 大概是这样的:
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的位置头并重定向到它。试着像这样返回
HttpResponseMessage
public HttpResponseMessage Get()
{
return Request.CreateErrorResponse(
HttpStatusCode.Unauthorized, "You are not authorized");
}
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"}
这将产生一个HTTP响应消息,如下所示
public HttpResponseMessage Get()
{
return Request.CreateErrorResponse(
HttpStatusCode.Unauthorized, "You are not authorized");
}
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"}
如果你使用普通的
$http
,会发生什么?卡洛斯,我同意使用普通的$http。如果我们确定$resource不能用于解决这个问题,我会这样做。已经确认了吗?我需要一个解决方案,可以抛出HttpResponseException
异常。您使用Request.CreateErrorResponse
的建议让我达到了目的。看起来像前面的代码I:抛出新的HttpResponseException(新的HttpResponseMessage(HttpStatusCode.Unauthorized){ReasonPhrase=mymessage})使用CreateErrorResponse
重写时,code>解决了以下问题:抛出新的HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized,mymessage))代码>这在WebAPI2BTW上不起作用,因为IHttpAcionResult是新的最佳实践。