Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 294
xlecoustillier Avatar asked Jan 28 '15 13:01

xlecoustillier


1 Answers

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());
like image 160
Darin Dimitrov Avatar answered Nov 16 '22 15:11

Darin Dimitrov