何时执行MVC ExceptionFilter与应用程序级错误处理程序?

oba*_*lis 8 c# model-view-controller asp.net-mvc-5

我有一个自定义异常FilterAttribute,如下所示:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class ExceptionLoggingFilterAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException(nameof(filterContext));
        }

        if (filterContext.ExceptionHandled)
        {
            return;
        }

        // some exception logging code (not shown)

        filterContext.ExceptionHandled = true;
}
Run Code Online (Sandbox Code Playgroud)

我在FilterConfig.cs中全局注册了这个

public static class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters?.Add(new ExceptionLoggingFilterAttribute());
    }
}
Run Code Online (Sandbox Code Playgroud)

我还在我的global.asax.cs中声明了一个Application_Error方法

protected void Application_Error(object sender, EventArgs e)
    {
        var exception = Server.GetLastError();

        // some exception logging code (not shown)
    }
Run Code Online (Sandbox Code Playgroud)
  1. 什么时候会触发异常过滤器代码,什么时候会直接进入Application_Error方法中的全局错误处理程序?(我理解ExceptionHandled概念并意识到通过标记在我的过滤器中处理,它将不会级联到全局错误处理程序).

我认为会遇到过滤器的一个例外 - 404的HttpException,没有命中过滤器但是会被应用程序错误处理程序捕获.

  1. 我见过一些代码示例,其中人们使用global.asax.cs中的HttpContext.Current对特定的错误视图执行Server.TransferRequest.这是最佳做法吗?使用web.config的system.web部分中的CustomErrors部分会更好吗?

Mar*_*kus 3

仅当 ASP.NET MVC 管道执行期间发生错误时,才会触发异常过滤器,例如在 Action 方法执行期间:

异常过滤器。这些实现 IExceptionFilter 并在 ASP.NET MVC 管道执行期间抛出未处理的异常时执行。异常过滤器可用于记录或显示错误页面等任务。HandleErrorAttribute 类是异常过滤器的一个示例。

(来自:https ://msdn.microsoft.com/en-us/library/gg416513( VS.98).aspx)

在出现 404 错误的情况下,无法确定 Action 方法,因此过滤器中不会处理该错误。

所有其他错误都将在该方法中处理Application_Error

至于问题的第二部分,我推荐以下博客文章,其中包含有关如何以可靠的方式设置自定义错误页面的良好概述: http://benfoster.io/blog/aspnet-mvc-custom -错误页面