I have a simple ASP.Net MVC 3 application that has some controller and a good few actions.
Now, as this is a user based application, most of the controller actions require the user to be authenticated. MVC handles this well with the built-in Authorize attribute which you can use to decorate controllers and/or actions individually.
The great thing is you can apply the attribute to just the controller and all actions for that given controller will have it applied too - lots of typing saved ;)
But I have one controller with, lets say, 10 actions. But I want one of the actions to not have the Authorize attribute applied.
Yes, I could apply the attribute to the other 9 and remove it from the controller which will do exactly what I need. But is there a way to keep it applied to the controller and just choose to exclude one of the actions?
Effectively, would want something like...
[!Authorize]
or [NotAuthorize]
I know I could create a custom one that will do the job, but what I want to know is if there is a built-in way to do this? or do I have to apply the attribute to all 9 other actions?
You could create a custom authorisation attribute inheriting from the standard AuthorizeAttribute with an optional bool parameter to specify whether authorisation is required or not. and for any controllers you don't want authorisation simply use the override with a 'false' - e.g.
If a user is not authenticated, or doesn't have the required user name and role, then the Authorize attribute prevents access to the method and redirects the user to the login URL. When both Roles and Users are set, the effect is combined and only users with that name and in that role are authorized.
Note that a new attribute has been added in ASP.NET MVC 4.0 that does exactly that:
[AllowAnonymous]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With