ELMAH and API controller in MVC4 not logging errors

Deadly 提交于 2019-12-03 02:27:58

The anwser described before doesn't work. I've tried on my test server and received an error ("The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter.")

Then I realized what happened .... you are trying to add the custom filter to the MVC Global Filter (filters.Add(new ElmahHandledErrorLoggerFilter());)

To fix that, I've split the filter registration in GlobalFilter and HttpFilter

FilterConfig.cs

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterHttpFilters(HttpFilterCollection filters)
    {
        filters.Add(new ElmahHandledErrorLoggerFilter());
    }

Global.asax

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    FilterConfig.RegisterHttpFilters(GlobalConfiguration.Configuration.Filters);

;-)

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());
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!