ELMAH and API controller in MVC4 not logging errors

前端 未结 2 846
情书的邮戳
情书的邮戳 2021-02-05 20:09

Using an API controller in MVC4, when the controller action throws an exception, ELMAH does not log the error.

I think the problem is that MVC4 sets the HTTP status code

2条回答
  •  南方客
    南方客 (楼主)
    2021-02-05 21:00

    UPDATE: This answer does not work in latest versions. Use julianox's answer.

    Answer found from information here: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

    Where the exception filter logs to elmah:

    public class ElmahHandledErrorLoggerFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);
    
            ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
        }
    }
    

    but you also have to add the error filter to the GlobalConfiguration filters:

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            GlobalConfiguration.Configuration.Filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new HandleErrorAttribute());
        }
    

提交回复
热议问题