MVC 4全局异常过滤器如何实现?

时间:2012-12-12 02:38:51

标签: asp.net-mvc asp.net-mvc-4

如何在MVC4中实现全局异常处理程序,因为它似乎与MVC3不同。

不确定如何实施以下内容:

public class ErrorHandlerAttribute: System.Web.Mvc.FilterAttribute, 
                                    IExceptionFilter
{
    public Task ExecuteExceptionFilterAsync(
            HttpActionExecutedContext actionExecutedContext, 
            CancellationToken cancellationToken)
    {
        throw new NotImplementedException();
    }
}

2 个答案:

答案 0 :(得分:31)

不幸的是,Eric Leschinski的commet中提供的链接仅显示了如何实现System.Web.Mvc.IExceptionFilter接口,而不是System.Web.Http.Filters.IExceptionFilter接口。第一个用于常规MVC控制器,而第二个用于ApiCotrollers

这是一个简单的类示例,用于记录在我的ApiControllers中抛出的未处理的异常:

public class ExceptionLoggerFilter: IExceptionFilter
{
    public ExceptionLoggerFilter(Logger logger)
    {
        this.logger = logger;
    }

    public bool AllowMultiple { get { return true; } }

    public Task ExecuteExceptionFilterAsync(
            HttpActionExecutedContext actionExecutedContext,
            CancellationToken cancellationToken)
    {
        return Task.Factory.StartNew(() =>
        {
            logger.Error("web service error", actionExecutedContext.Exception);
        }, cancellationToken);
    }

    private Logger logger;
}

要启用此过滤器,您需要做的就是在您的Global.asax Application_Start方法中注册它:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // allocate filter and add it to global configuration
    var exceptionLogger = new ExceptionLoggerFilter(Container.Get<Logger>());
    GlobalConfiguration.Configuration.Filters.Add(exceptionLogger);

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

我希望这有助于其他googlers在那里!

答案 1 :(得分:11)

我为MVC部分创建了一个异常处理程序,我创建了一个实现了IExceptionFilter的类

public class MVCExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        Trace.TraceError(filterContext.Exception.ToString());
    }
}

然后在Global.asax.cs中注册它 在protected void Application_Start()

该方法已包含行

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

因此,您需要添加此行 ABOVE it

GlobalFilters.Filters.Add(new MVCExceptionFilter());