开发者

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

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?


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")


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜