【发布时间】: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)
}
- 什么时候会触发异常过滤器代码,什么时候会直接进入 Application_Error 方法中的全局错误处理程序? (我理解 ExceptionHandled 的概念,并意识到通过在我的过滤器中将其标记为已处理,它不会级联到全局错误处理程序)。
我认为会命中过滤器的异常 - 404 的 HttpException 未命中过滤器,但会在应用程序错误处理程序中捕获。
- 我已经看到一些代码示例,其中人们使用 global.asax.cs 中的 HttpContext.Current 对特定错误视图执行 Server.TransferRequest。这是最佳实践吗?使用 web.config 的 system.web 部分中的 CustomErrors 部分会更好吗?
【问题讨论】:
标签: c# model-view-controller asp.net-mvc-5