何时执行 MVC 异常筛选器与应用程序级错误处理程序?



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

我在我的过滤器配置中全局注册了这个.cs

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

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

protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
// some exception logging code (not shown)
}
  1. 何时会命中异常筛选器代码,何时会直接进入 Application_Error 方法中的全局错误处理程序?(我理解 ExceptionHandle 的概念,并意识到通过在我的过滤器中将其标记为已处理,它不会级联到全局错误处理程序)。

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

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

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

异常筛选器。这些实现IExceptionFilter并执行,如果 在执行 ASP.NET MVC 管道。异常筛选器可用于以下任务: 记录或显示错误页面。类是 异常筛选器的一个示例。

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

在 404 错误的情况下,无法确定 Action 方法,因此不会在筛选器中处理错误。

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

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

最新更新