MVC 4 Global Exception Filter how to implement?

前端 未结 2 412
孤城傲影
孤城傲影 2020-12-30 04:54

How do I implement a global exception handler in MVC4 as it seems to be different from MVC3.

Not sure how to implement the following:

public class E         


        
相关标签:
2条回答
  • 2020-12-30 05:02

    The way I created an exception handler for MVC part of it, I created a class that implemented IExceptionFilter

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

    You then register it in the Global.asax.cs inside protected void Application_Start()

    The method already contains the line

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    

    So, you will need to add this line ABOVE it

    GlobalFilters.Filters.Add(new MVCExceptionFilter());
    
    0 讨论(0)
  • 2020-12-30 05:13

    Unfortunately the link provided in Eric Leschinski's commet only shows how to implement the System.Web.Mvc.IExceptionFilter interface, and not the System.Web.Http.Filters.IExceptionFilter interface. The first is used in regular MVC controllers, while the second targets ApiCotrollers.

    Here is a simple class example I came up with for logging unhandled exceptions thrown in my 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;
    }
    

    And all you have to do to enable this filter is register it in yours Global.asax Application_Start method:

    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);
    }
    

    I hope this helps other googlers out there!

    0 讨论(0)
提交回复
热议问题