Prevent a ASP.NET MVC global filter from being applied on Elmah action

柔情痞子 提交于 2019-12-23 07:33:23

问题


I'm using Elmah for logging exceptions on my MVC application using Alex Beletsky's elmah-mvc NuGet package.

The application registers some global filters, applied on each action called.

Is there a way to prevent some of those filters from being applied when calling the Elmah.Mvc.ElmahController error log page (foo.com/elmah) ?

A test like below works, of course, but I'm looking for a more elegant way that would not involve modifying the filter (nor the source code from Elmah / Elmah MVC). Is it even possible ?

public class FooAttribute : FilterAttribute, IActionFilter
{
    // ...

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.Controller is ElmahController)
        {
            return;
        }

        // do stuff
    }
}
  • I know that attributes can't be added or removed at runtime.

  • I thought of wrapping the ElmahController in a new one where I could add an exclusion filter, but I'm not sure how (if possible) to change the web.config to reference this wrapper instead of the original controller.


回答1:


You could register your global filters through a custom IFilterProvider:

public class MyFilterProvider : IFilterProvider
{
    public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (controllerContext.Controller is ElmahController)
        {
            return Enumerable.Empty<Filter>();
        }

        return ... the collection of your global filters
    }
}

and in your Application_Start instead of calling:

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

you would call:

FilterProviders.Providers.Add(new MyFilterProvider());


来源:https://stackoverflow.com/questions/28193082/prevent-a-asp-net-mvc-global-filter-from-being-applied-on-elmah-action

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