Albeit I like Darin s answer it doesn t work in our case since the ASP.NET MVC Web API framework is suppressing/handling exceptions internally and not re-throwing to hit the Application_Error method in the Global.asax. Our solution is this.
我最后提出了一种习俗,即:
public class PrincipalHandler : DelegatingHandler
{
protected const string PrincipalKey = "MS_UserPrincipal";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
setAnonymousPrincipal();
request = InitializeIdentity(request);
return base.SendAsync(request, cancellationToken)
.ContinueWith(r =>
{
// inspect result for status code and handle accordingly
return r.Result;
});
}
}
I then inserted it into the HttpConfiguration to make sure it is the first/last handler to be hit. The way handlers work in the Web API is in a hierarchical fashion. So the first handler to be hit per request, will be the last handler to be hit on the response. At least this is my understanding, someone feel free to correct me if I m wrong.
public static void ConfigureApis(HttpConfiguration config)
{
config.MessageHandlers.Insert(0, new PrincipalHandler());
}
通过采用这一方法,我们现在可以检查从网络信息预报和管制人员回复中得出的每一项结果。 这使得我们能够处理任何可能由于我们所期望的不归还而发生的伐木。 我们现在还可以改变回复的内容,以便国际独立调查局在发现某些《吉大港山区行动计划》的状态代码时,插入任何不实的超文本错误页。
The only problem I have with this, and I m hoping they change it in an upcoming release of the web API, is that they aren t sending the exception back up on the Task being returned from base.SendAsync(). So the only information we have to go by is the HTTP status code and try our best to give a reasonable or probable answer to the consumer.