【问题标题】:When will an MVC ExceptionFilter be executed vs the application-level error handler?MVC ExceptionFilter 与应用程序级错误处理程序何时执行?
【发布时间】:2017-10-22 04:07:47
【问题描述】:

我有一个自定义异常 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;
}

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

public static class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters?.Add(new ExceptionLoggingFilterAttribute());
    }
}

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

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

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

我认为会命中过滤器的异常 - 404 的 HttpException 未命中过滤器,但会在应用程序错误处理程序中捕获。

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

【问题讨论】:

    标签: c# model-view-controller asp.net-mvc-5


    【解决方案1】:

    只有在 ASP.NET MVC 管道执行期间发生的错误才会命中异常过滤器,例如在执行 Action 方法期间:

    异常过滤器。这些实现 IExceptionFilter 并执行 if 执行过程中抛出未处理的异常 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-error-pages

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      相关资源
      最近更新 更多