本文介绍了异常处理ASP.NET MVC的Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会,是的,我们已经建立并正在使用的异常过滤器从ExceptionFilterAttribute继承开始。它是注册在应用程序启动时的配置我们的身份后,过滤器和右作品pretty如果我们的API内的某处发生错误预期多。

I'll start off with, yes, we have created and are using an exception filter inheriting from the ExceptionFilterAttribute. It is registered in the config on app startup right after our identity filter and works pretty much as expected if an error occurs somewhere inside our API.

话虽这么说,我正在寻找一种方法来处理这​​种情况发生到达API之前的错误。

That being said, I'm looking for a way to handle errors that happen before it reaches the API.

推理::我们从来不想返回YSOD和/或IIS HTML错误。我们总是想打一个自定义异常过滤器/处理器使我们能正确处理记录,并返回一个JSON响应用户。

Reasoning: We never want to return a YSOD and/or IIS HTML error. We ALWAYS want to hit a custom exception filter/handler so that we can handle logging correctly and return a JSON response to the user.

截至目前,使用招提出请求,我​​可以附加到W3wp.exe进程,看到了要求打在Global.asax中的Application_BeginRequest方法。在此之后,它只是返回一个500响应。它从来没有在code打破了异常或后打我的任何破发点。这似乎是返回一个错误IIS。我们不希望这种情况发生。我们需要的能力来捕获所有这些低层次的例外,记录它们,并返回一些有意义的事给用户。

As of right now, using Fiddler to make a request, I can attach to the w3wp.exe process and see the request hit the Application_BeginRequest method in the global.asax. After that, it just returns a 500 response. It never breaks in code with an exception or hits any of my break points after that. It seems to be returning an IIS error. We never want this to happen. We need the ability to catch all of these "low-level" exceptions, log them, and return something meaningful to the user.

有什么我们可以做前处理错误,似乎是击中ASP.NET MVC的Web API code?

Is there something we can do to handle errors before, what seems to be hitting the ASP.NET MVC Web API code?

推荐答案

尽管我很喜欢达林的回答是不会,因为ASP.NET MVC的Web API框架我们的情况下工作燮pressing /处理异常和内部不能再扔砸在Global.asax Application_Error事件。我们的解决方案是这样的。

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.

我结束了创建一个自定义DelegatingHandler像这样:

I ended up creating a custom DelegatingHandler like so:

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;
                              });
    }
}

然后我插入HttpConfiguration,以确保它是被打的第一个/最后一个处理程序。处理程序在Web API中的工作方式是分层方式。因此,为每个请求被击中的第一个处理程序,将在回应被打的最后一个处理。至少这是我的理解,有人随时纠正我,如果我错了。

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());
}

通过使用这种方法,我们现在可以检查每个结果回来从网络API和控制器任何回应。这使我们能够处理可能需要发生作为,因为我们预计在返回的东西而产生的任何记录。现在,我们还可以改变回来的响应的内容,使IIS不插入任何默认HTML错误页面,如果它认为某些HTTP状态codeS。

By using this approach we can now inspect every result coming back in any response from the web API and controllers. This allows us to handle any logging that may need to occur as a result of something not being returned as we expect. We can now also alter the content of the response coming back so that IIS doesn't insert any default HTML error pages if it sees certain HTTP status codes.

唯一的问题我有这一点,我希望他们改变它在即将到来的网络API释放,是他们没有发出异常备份的任务从base.SendAsync返回() 。因此,我们必须去的唯一信息是HTTP状态code和尽力给出一个合理的或可能的答案给消费者。

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.

这篇关于异常处理ASP.NET MVC的Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:36
查看更多