Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce Action Filter on all Controller Actions (C# / ASP.NET MVC)

I made a new action filter (attribute, similar to [Authorize]) which authorizes access to a controller action based on a session value. However, I'm basically decorating all my controller actions with that attribute (with the exception of very few).

So, I thought it would be better to have that Action Filter always executed except in cases where I attach an [ExemptFromAuthorize] attribute to a controller action? (Maybe via inheriting to my own Controller class?)

How can I do this?

like image 773
Alex Avatar asked Aug 27 '09 20:08

Alex


People also ask

What step is required to apply a filter globally to every action in your application?

As Global Filter You need to add your filter globally, to add your filter to the global filter. You first need to add it on Global. asax file. You can use FilterConfig.

What is ActionFilterAttribute?

The Base ActionFilterAttribute Class Technically, a class that inherits from the ActionFilterAttribute class is both an action filter and a result filter. However, in the loose sense, the word action filter is used to refer to any type of filter in the ASP.NET MVC framework.

Can we set custom action filter in action methods in Web API?

Now we can modify our web API controller to add the Action Filter we have just created.An Action Filter can modify a whole class: in that case all the methods in the API Controller are affected. Or we can set it to affect only a determined class.


2 Answers

For anyone reading this in 2013+, MVC4 now supports the use of [AllowAnonymous]

You can put Authorize on the controller, and then Allow Anonymous on any functions you do not want to authorize.

Example:

[Authorize] public class HomeController : Controller {

[AllowAnonymous]
public ActionResult Index()
{

} 

}

Would this work with a custom [MyAuthorize] filter or does it only work with [Authorize]

like image 105
lanierhall Avatar answered Oct 27 '22 01:10

lanierhall


For anyone reading this in 2013+, MVC4 now supports the use of [AllowAnonymous]

You can put Authorize on the controller, and then Allow Anonymous on any functions you do not want to authorize.

Example:

[Authorize]
public class HomeController : Controller
{

    [AllowAnonymous]
    public ActionResult Index()
    {

    }
}
like image 34
Kyle Avatar answered Oct 27 '22 01:10

Kyle