Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 GlobalFilters Exclude

I have a filter that would like to apply to all controllers except for one. So I am trying to write something that looks like this:

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
 {
     filters.Add(new MySweetAttribute()).Exclude(OneController);
 }

Trying to read through Brad's post on the subject is gibberish to me

http://bradwilson.typepad.com/blog/2010/07/service-location-pt4-filters.html

I am assuming it is possible since the library below seems to do it, but I would like to avoid adding a dependency if possible.

http://www.codeproject.com/KB/aspnet/FluentFltrsASPNETMVC3.aspx

Hoping someone has done this already and it is easy to do...

Thanks for any help.

Update

Phil Haack has just posted how to approach this scenario.

http://haacked.com/archive/2011/04/25/conditional-filters.aspx

like image 441
B Z Avatar asked Feb 21 '11 20:02

B Z


2 Answers

I've been searching the web for the same question without luck so I just tried this myself and it works:

public class MySweetAttribute: ActionFilterAttribute
{
    public bool Disable { get; set; }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (Disable) return;

        ...
    }
}

Then, when you want to disable the global filter, just add the attribute to the action with the disable propierty set to true:

[MySweetAttribute(Disable=true)]
public ActionResult Index()
{            
    return View();
}

Hope this help

like image 91
eledu81 Avatar answered Sep 28 '22 06:09

eledu81


I think you will need to implement a filter provider to do this, then when you implement GetFilters do not apply the filter for the action you wish to exclude. Here is an example:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=578

like image 29
Joe Cartano Avatar answered Sep 28 '22 08:09

Joe Cartano