ASP.Net MVC 3: reverse authorization attribute

I have a simple ASP.Net MVC 3 application with some controller and several actions.

Now, since this is a user application, most controller actions require the user to be authenticated. MVC handles the built-in Authorize attribute well, which you can use to customize your controllers and / or actions.

The great thing is that you can only apply the attribute to the controller, and all actions for this controller will also be applied - a lot of input is saved;)

But I have one controller, say 10 actions. But I want one of the actions to not include the Authorize attribute.

Yes, I could apply the attribute to another 9 and remove it from the controller, which will do exactly what I need. But is there a way to save it in relation to the controller and simply exclude one of the actions?

Effectively, I would like something like ...

[!Authorize] or [NotAuthorize]

I know that I can create a custom one that will do the job, but I want to know if there is a built-in way to do this? or do I need to apply the attribute to all 9 other actions?

+7
source share
2 answers

Phil Haack wrote a blog post recently related to this exact scenario:

Conditional filters in ASP.NET MVC 3

His solution includes a user-defined “conditional filter provider” record that allows you to assign a filter condition to the attributes of an action method.

Details and reasoning are in his post, but the code is relatively simple. First create a filter provider:

 using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; public class ConditionalFilterProvider : IFilterProvider { private readonly IEnumerable<Func<ControllerContext, ActionDescriptor, object>> _conditions; public ConditionalFilterProvider( IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions) { _conditions = conditions; } public IEnumerable<Filter> GetFilters( ControllerContext controllerContext, ActionDescriptor actionDescriptor) { return from condition in _conditions select condition(controllerContext, actionDescriptor) into filter where filter != null select new Filter(filter, FilterScope.Global, null); } } 

And then applying it:

 IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions = new Func<ControllerContext, ActionDescriptor, object>[] { (c, a) => c.Controller.GetType() != typeof(HomeController) ? new MyFilter() : null, (c, a) => a.ActionName.StartsWith("About") ? new SomeFilter() : null }; var provider = new ConditionalFilterProvider(conditions); FilterProviders.Providers.Add(provider); 
+2
source

Note that a new attribute was added in ASP.NET MVC 4.0 , which does just that:
[AllowAnonymous]

+10
source

All Articles