1
我正在使用MVC 4 Web API框架编写Web API。我正在使用BASIC
身份验证,并使用从DelegatingHandler
继承的自定义身份验证消息处理程序。在身份验证处理程序中设置响应错误
除了我的错误处理,一切都很好用。
我使用Web API作为现有认证机制的包装,并在用户密码过期时引发异常。在API的操作方法,我可以抛出一个HTTPResponseException轻松地处理这一点,我得到一个整洁的小JSON对象,如下图所示:
{
"Message": "Password is expired."
}
如果我尝试同样的方法在我的验证消息处理程序,我得到所有令人讨厌的.NET响应输出。
<html>
<head>
<title>Processing of the HTTP request resulted in an exception. Please see the HTTP response returned by the 'Response' property of this exception for details.</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
... you get the idea ...
我想我已经接近...在SendAsync
catch (Exception ex)
{
var response = request.CreateErrorResponse(HttpStatusCode.Unauthorized, ex.Message);
response.Headers.Add("WWW-Authenticate", "Basic realm=\"myrealm\"");
}
这里,也许如果我能以某种方式从我的响应对象中获取Task<HttpResponseMessage>
回来,我想我可能是好的。
基本上我的问题是“应该如何处理异常,以便我能够向用户返回一个不错的json/xml对象?”
还有一点要注意,这是.NET 4,而不是4.5。我已经看到几个使用await
关键字的示例,但在这种情况下不起作用。
辉煌,谢谢! – earthling