标签:
在REST服务中,服务端如果产生了异常信息,无论是业务异常或是系统异常,如果直接将异常抛出,在客户端浏览器中,是无法获取异常的详细,只能获取一个StateCode 500 Internal Server Error错误,如下:
HTTP/1.1 500 Internal Server Error Content-Length: 56 Content-Type: text/xml; charset=utf-8 Server: Microsoft-HTTPAPI/2.0 Date: Tue, 14 Jul 2015 13:22:15 GMT <Error><Message>An error has occurred.</Message></Error>
如需要在客户端获取服务端的详细异常信息,需要如下定义异常信息:
var resp = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new StringContent("Not allowed to delete this resource"), ReasonPhrase = "forbidden" }; throw new HttpResponseException(resp);
抛出HttpResponseException即可在客户端(浏览器,调试工具如Fiddler)中进行捕获并进行对应处理,如下所示:
HTTP/1.1 403 forbidden Content-Length: 35 Content-Type: text/plain; charset=utf-8 Server: Microsoft-HTTPAPI/2.0 Date: Tue, 14 Jul 2015 13:26:38 GMT Not allowed to delete this resource
标签:
原文地址:http://www.cnblogs.com/JiaK/p/4646644.html