Can I set a custom class as the default base class for my controllers in ASP.NET MVC3?

1.2k views Asked by At

I'd like to inherit all my controllers from a custom base class that I write myself. I can change the line every time I add a new controller, but it would be nicer if I could somewhere specify the default value that gets set there. That way I wouldn't need to worry about forgetting this, and other people who get added to the project later on would have an easier time.

Is there any way to achieve this?

3

There are 3 answers

4
marcind On BEST ANSWER

You can customize the T4 template that gets used when the Add Controller action gets invoked. Basically you would have to copy the template from C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates\AddController\Controller.tt to '~\CodeTemplates\AddController\Controller.tt` in your project file.

More info available here (scroll down to "Adding and Customizing Scaffold Templates")

1
Kassem On

Yup that's an easy task to do. First create a class called "BaseController" for example which inherits from Controller. Then all your controllers would inherit from BaseController.

EDIT: I think that using a T4 template to generate your costume controller (called BaseController or maybe Controller - whichever you prefer) would also work. I've seen Scot Hanselman do something similar in one of his talks.

1
Rob West On

You could do this using namespaces: create a class called Controller in the same namespace as your controllers, e.g.:

namespace UI.Controllers
{
    public class Controller : System.Web.Mvc.Controller
    {
        //Code here
    }
}

and then the standard unqualified references to Controller will reference your base class instead of the System.Web.Mvc.Controller one.

Might get confusing though - I'd rather just have to remember to reference the base class.