Attributes on Areas in ASP.NET MVC 2?
The "Admin" area in my app contains a bunch of controllers, and it's a bit repetitive to put an [Authorize]
attribute on all of them. Is there a way of telling the framework that all controllers in a certain area should have certain attributes?
Edit: Inheritance is not a solution in this case. First of all the controllers already inherits from a custom class, and secondly, it sh开发者_运维百科ould be about decorating the classes, not inheriting them.
MVC 3 has a new feature called Global Action Filters which would be perfect for what you are doing. Since you're probably not on MVC 3 yet, you can also implement Global Action Filter in earlier versions of MVC by following this example. Just customize the solution to filter check if you are in the "Admin" area for the currently executing request, then apply your Authorize attribute.
This will allow you to do this without having to apply a common base class as you requested.
You could create a base controller that all controllers in this area derive from and decorate it with the [Authorize]
attribute.
There are four options,
- Create a separate base controller and make admin sectionsu inherit from it
- Add the Authorise Attribute to the controller class instead of each method / Actrion
- Decorate each on individually
- write your own logic for authorization and add that to your current base controller
精彩评论