在我的WebAPI类ApiController
中,我进行了如下调用:
string myCustomMessage = .....;
throw new HttpResponseException(
new HttpResponseMessage(HttpStatusCode.Unauthorized)
{ ReasonPhrase = myCustomMessage });
当我使用AngularJS
$resource
服务进行调用时,我确实在状态字段中获得401的响应,即promise的catch块中的响应。 401匹配HttpStatusCode.Unauthorized
,所以一切顺利。但是,问题在于响应的数据字段为空(空)。我没有得到myCustomMessage返回。
现在,如果我没有抛出
HttpResponseException
异常,而只是抛出一 strip 有消息的常规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"}