I've seen a lot of people talk about using base controllers in their ASP.NET MVC projects. The typical examples I've seen do this for logging or maybe CRUD scaffolding. What are some other good uses of a base controller class?
10 Answers
There are no good uses of a base controller class.
Now hear me out.
Asp.Net MVC, especially MVC 3 has tons of extensibility hooks that provide a more decoupled way to add functionality to all controllers. Since your controllers classes are very important and central to an application its really important to keep them light, agile and loosely coupled to everything else.
Logging infrastructure belongs in a constructor and should be injected via a DI framework.
CRUD scaffolding should be handled by code generation or a custom ModelMetadata provider.
Global exception handling should be handled by an custom ActionInvoker.
Global view data and authorization should be handled by action filters. Even easier with Global action filters in MVC3.
Constants can go in another class/file called ApplicationConstants or something.
Base Controllers are usually used by inexperienced MVC devs who don't know all the different extensibility pieces of MVC. Now don't get me wrong, I'm not judging and work with people who use them for all the wrong reasons. Its just experience that provides you with more tools to solve common problems.
I'm almost positive there isn't a single problem you can't solve with another extensibility hook than a base controller class. Don't take on the the tightest form of coupling ( inheritance ) unless there is a significant productivity reason and you don't violate Liskov. I'd much rather take the < 1 second to type out a property 20 times across my controllers like public ILogger Logger { get; set; }
than introduce a tight coupling which affects the application in much more significant ways.
Even something like a userId or a multitenant key can go in a ControllerFactory instead of a base controller. The coupling cost of a base controller class is just not worth it.

- 55,572
- 24
- 139
- 212

- 24,673
- 10
- 77
- 110
-
4Ok we can do things without using base controller. Could you please tell some disadvantages of using base controller – Tassadaque May 26 '11 at 06:30
-
9@Tassadaque - Coupling, coupling, coupling and coupling. – John Farrell May 26 '11 at 13:07
-
44I'm not convinced. You prefer having the same code in all your controllers over having a base controller, so there must be an advantage to this. You say the advantage is "loose coupling", but what exactly does that mean, which problems does it solve, what does it do except decoupling for the sake of decoupling? – user247702 Feb 13 '13 at 13:18
-
4I'm not sure that I agree here but there is a lot of food for thought here so +1. I tend to think a base controller could be used in conjunction with action filters etc. If subclass wants to overwrite said method there is nothing stopping it. – Nick Van Brunt Mar 20 '13 at 13:35
-
5I don't understand the argument made here. Sure unnecessary coupling is something to avoid, but like with everything else it's a choice that is dependent on the current situation and will have scenarios where the benefit is bigger then the cost. Inheritance can provide you with a low-cost single point of common logic and reduce code and surface area for human mistakes, _if_ this generalization actually makes sense. I don't think anyone is arguing that you should try to use base classes for _everything_ you can do with attributes. – Alex Aug 31 '14 at 03:52
-
@jfar I've been trying to find an alternative for the case where you have a custom IPrincipal that needs to be cast to CustomPrincipal at the beginning of every controller action in order to access your custom properties. A base controller alleviates the need for this type of boilerplate code, but I hate that it seems to be the only mechanism. The only other mechanism I can think of is to create an ActionFilter that casts the IPrincipal to CustomPrincipal, and sets it as an ActionParameter. Is there another solution? – crush Jun 19 '15 at 19:50
-
1Just to play devil's advocate, there is one good use of a base controller: a generic base controller. If there's a lot of similar functionality between different controllers with the only major difference being a type in play (admin-style controllers, for example), then having a generic abstract base controller could be a very good idea, actually. However, other than that I totally agree with you. – Chris Pratt Feb 14 '17 at 14:22
-
1I think it's worth hedging terminology as well. There are no good uses for a *global* base controller that every single controller must depend on. However, there could very well be uses for controller inheritance, in general, just not globally. – Chris Pratt Feb 14 '17 at 14:30
-
@jfar your answer is really confusing, what would be your answer in 2018? What is wrong with having a generic base controller that removes boilerplate logic? – Konrad May 25 '18 at 14:58
-
For example `CrudController
: Controller` – Konrad May 25 '18 at 15:00 -
What would be your answer when using a modern framework like ASP.NET Core – Konrad May 25 '18 at 15:11
-
@Konrad, What about asp.net core would change the answer? IMHO the ever-increasing amount of extensibility points means that a base controller is even more of a mistake. – John Farrell May 31 '18 at 21:12
-
@jfar there's no real rational reason why you shouldn't use base controllers – Konrad May 31 '18 at 21:59
-
your answer doesn't make much sense to me – Konrad May 31 '18 at 21:59
-
1extensibility points are one thing, base controllers are more for reusability than extensibility, I'm not going to write the same CRUD actions everywhere when I can just derive from my `CrudController` that already implements all the logic that goes down to my service layer – Konrad May 31 '18 at 22:01
-
my controllers are usually very thin just passing calls to some other layer like a service layer, or sending a command using MediatR and the rest is handled in some handlers. – Konrad May 31 '18 at 22:02
-
3There are better ways to compose that behavior instead of as a base class. You may want to google "composition vs inheritance" for a better primer on the subject than SO comments will allow. – John Farrell Jun 05 '18 at 16:43
I like to use base controller for the authorization.
Instead of decorating each action with "Authorize" attribute, I do authorization in the base controller. Authorized actions list is fetched from database for the logged in user.
please read below link for more information about authorization. Good practice to do common authorization in a custom controller factory?
-
You could just add a global filter or decorate the controller itself? If you need granularity, use policy. Edit: Oh, this answer is from 2011 :-) Sorry. – Jonas Stensved Jan 05 '21 at 21:37
I have used base controller in many of my projects and worked fantastic. I mostly used for
- Exception logging
- Notification (success, error, adding..)
- Invoking HTTP404 error handling

- 53
- 1
- 7
-
would u redirect me to few article like how to handle your situation by base controller. situations are like `Exception logging, Notification (success, error, adding..) and HTTP404 error handling` thanks – Mou Sep 15 '15 at 13:38
I use it for accessing the session, application data etc.
I also have an application object which holds things like the app name etc and i access that from the base class
Essentially i use it for things i repeat a lot
Oh, i should mention i don't use it for buisiness logic or database access. Constants are a pretty good bet for a base class too i guess.

- 22,624
- 33
- 128
- 205
What i did was to use a generic controller base class to handle:
- I created
BaseCRUDController<Key,Model>
which required aICRUDService<TModel>
object as constructor parameter so the base class will handle Create / Edit / Delete. and sure in virtual mode to handle in custom situations - The
ICRUDService<TModel>
has methods like Save / Update / Delete / Find / ResetChache /... and i implement it for each repository I create so i can add more functionality to it. - using this structure i could add some general functionality like PagedList / AutoComplete / ResetCache / IncOrder&DecOrder (if the model is IOrderable)
Error / Notification messages handling: a part in Layout with
@TempData["MHError"]
code and a Property in base Controller likepublic Notification Error { set { TempData["MHError"] = value; } get { return (Notification) TempData.Peek("MHError"); } }
With this Abstract classes i could easily handle methods i had to write each time or create with Code Generator. But this approach has it's weakness too.

- 649
- 2
- 7
- 22
From my experience most of the logic you'd want to put in a base controller would ideally go into an action filter. Action Filter's can only be initialized with constants, so in some cases you just can't do that. In some cases you need the action to apply to every action method in the system, in which case it may just make more sense to put your logic in a base as opposed to annotating every action method with a new actionFilter attribute.
I've also found it helpful to put properties referencing services (which are otherwise decoupled from the controller) into the base, making them easy to access and initialized consistently.

- 1,951
- 4
- 16
- 25
-
2It's not true that ActionFilters can only be initialized with constants. The initialization of constants is a feature of Attributes, rather than the IActionFilter interface. You can create your action filter, and then assign it to the GlobalFilterCollection in your filter config, or wherever you handle such things. In your filter, you'd then simply check for the existence of a separate attribute you created, before continuing with the logic of the filter. – crush Jun 19 '15 at 19:53
We use the BaseController for two things:
- Attributes that should be applied to all Controllers.
- An override of Redirect, which protects against open redirection attacks by checking that the redirect URL is a local URL. That way all Controllers that call Redirect are protected.

- 346
- 3
- 5
-
your second point is not very clear. how to override redirect in base controller? would come up with some example like how to do it. would educate me if possible about how open redirection attacks happen and how it can be prevent by base class by example. thanks – Mou Sep 15 '15 at 13:36
-
1) This could be done with [globally registered filters](https://msdn.microsoft.com/en-us/library/gg416513(VS.98).aspx) instead. Even better, custom filters can use custom attributes to conditionally exclude them (which would be a nightmare to maintain in a base controller with overriding). 2) This isolated logic could be placed into an extension method of the `Controller` class. No need to inherit a custom base controller everywhere (nor worry about eventually forgetting to do so somewhere). – NightOwl888 Jun 01 '16 at 16:30
Filter is not thread safe, the condition of database accessing and dependency injection, database connections might be closed by other thread when using it.

- 57
- 1
- 5
We used base controller:
- to override the
.User
property because we use our own User object that should have our own custom properties. - to add global
OnActionExecuted
logic and add some global action-filters

- 53,710
- 19
- 160
- 149