views:

49

answers:

4

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 should be about decorating the classes, not inheriting them.

+1  A: 

You could create a base controller that all controllers in this area derive from and decorate it with the [Authorize] attribute.

Darin Dimitrov
The inheritance chain is already busy unfortunately. :)
ciscoheat
Oh, so you have an inheritance chain. Well then simply go to the base controller(s) and decorate :-)
Darin Dimitrov
My base controller is shared between public and private areas...
ciscoheat
Ouch, well, then introduce an intermediary base controller that derives from this base controller and make the controllers in the area derive from the intermediary controller (wow what a sentence :-)).
Darin Dimitrov
I've considered that before, honestly. But to make things even more complicated, the base class is generic of type RestController<T>. So I need an AdminRestController<T> which feels outright strange, and that also doesn't cover the admin controllers that doesn't need a RestController. So I hope you understand there is a good reason for decoration, not inheritance. :)
ciscoheat
A: 

There are four options,

  1. Create a separate base controller and make admin sectionsu inherit from it
  2. Add the Authorise Attribute to the controller class instead of each method / Actrion
  3. Decorate each on individually
  4. write your own logic for authorization and add that to your current base controller
Dusty Roberts
+1  A: 

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.

Steve Michelotti
Great stuff, thanks!
ciscoheat