Reputation: 33978
In my old days when I was an asp.net webforms developer I used to create a basepage and in there I used to put common methods and properties that would be used in the application, then every page would inherit from that page.
I wonder how to do it for mvc 4, is there any guideline, or just create a base controller class and inherit all controllers from that class?
What do you usually put in the base controller class?
thanks
Upvotes: 3
Views: 2789
Reputation: 19465
There isn't really much a practise doing this. A lot of people coming from years of web forms think this way.
In our pretty big application, we created a BaseController
but didn't really see a way to encapsulate common behaviour into it.
However, eventually we did put a some common code to log exceptions by overriding the OnException method in a base controller
So I think you should go by : If you see code you can encapsulate, do it. You can make private methods inside the base controller but you cannot create a common action method in your base controller. You need to just encapsulate the code in a protected method, then you'll need an individual Action method in your concrete controller.
Upvotes: 1
Reputation: 16348
I avoid using a base controller (inheritance) for this problem, because it kinda smells. Are you sure your controllers need ALL those common methods and properties? At least some of the functionality can be implemented as extension methods on the Controller type.
Also other functionality might be more suitable as a service injected into the controller. For common methods that require some (request)state I prefer the service approach.
It's also possible that at least some functionality to belong to an action filter (checking rights, setting some user profile, handling exceptions ;) etc ).
As a thumb rule, I try to avoid using inheritance with my controllers. The controllers should be as simple as they can be and any utility behavior I'd need, I try to encapsulate it in one of the ways presented above.
Upvotes: 4