user20358
user20358

Reputation: 14766

using a base controller for entire asp.net MVC 4 project

I am thinking of using a base controller for the entire MVC 4 project that I am working on. I have found conflicting views online about it and not really sure if it is against best practices or if it is just a matter of personal preference.

Here is a stackoverflow post that says dont do it

Here is a post that has shown how to do it like there are no harmful effects of it. Here and here as well they explain its usage where no one really is pointing out that it is bad practice or could lead to any issues going forward.

So what really is the view on using a couple of base controllers in an MVC 4 project? Good? Bad?

Edit

I'd also like to point out that my immediate goal for using a base controller is so that I can have the Authorization done in one controller and so that all the controllers dont need to have the Authorize attribute. I will create separate base controllers for each role. Since the roles are never going to change I will never need to create another base controller for another role. What do you think of this way of going about designing the controllers?

Thanks for your time.

Upvotes: 9

Views: 13470

Answers (2)

eiximenis
eiximenis

Reputation: 638

IMHO what the post you reference says is absolutely true, but that's not a reason to not use a base controller. In fact I use a base controller in some of my ASP.NET MVC applications because of commodity.

This is no longer advisable:

Having a base controller to apply the [Authorize] attribute once is a common practice, and I don't see anything wrong on it.

Since MVC3 you can register global action filters like this:

GlobalFilters.Filters.Add(new MyAuthorizeAttribute());

Upvotes: 4

Tom Chantler
Tom Chantler

Reputation: 14951

I have used a base controller before when dealing with things like overriding the User principal (see here for an old question of mine describing the idea: Is this Custom Principal in Base Controller ASP.NET MVC 3 terribly inefficient?).

I honestly couldn't think of a better way of doing this, so I feel that in this kind of scenario using a base controller can be a good thing.

I probably wouldn't have different base controllers for different authorization roles though as it is fairly simple (and less code) just to decorate the controller with [Authorize(Roles="whatever")] and it will be easier to see exactly what is happening.

It may be worth considering a custom AuthorizeAttribute.

Upvotes: 3

Related Questions