Is the controller name derived from the class name?

我们两清 提交于 2019-12-22 06:36:34

问题


This is a newbie question...

I am looking at the default asp.net mvc3 project and noticed that there is a controller called:

public class AccountController : Controller

I looked throughout the code and couldn't find a place that specified AccountController maps to /Account/ for the URL.

I discovered that you can change the routing using routes.MapRoute(..) in the Global.asax, but I still don't know where they specified that AccountController maps to /Account/.

If it is assumed from the class name, then does that mean all controller classes have to be named xxxxxController?


回答1:


Yes you are right, all controllers need to follow the naming convention of an ending "Controller".

See the ControllerName property in the ASP.NET MVC code on CodePlex:

public virtual string ControllerName {
    get {
        string typeName = ControllerType.Name;
        if (typeName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            return typeName.Substring(0, typeName.Length - "Controller".Length);
        }
        return typeName;
    }
}

Anyhow, you could change the naming convention by using your own controller factory.

Hope that helps.




回答2:


Yes, this is a key aspect of the MVC framework called CoC, Convention over Configuration. The idea is that, as long as you are willing to follow the default conventions for things like class names, method names, folder structure, etc., you can minimize the amount of work you need to do for things to work. You only put in effort if you want to deviate from those conventions, which you certainly can do.

There are a number of such items in the MVC framework. In addition to the convention that all controllers are classes named XxxxController, there is the convention that all views are found in a folder named View\Xxxx\Yyyyy.cshtml.




回答3:


Yes it does, unless you implement your own Controller factory.



来源:https://stackoverflow.com/questions/6766598/is-the-controller-name-derived-from-the-class-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!