Forgot the suffix Controller in derived class - why the compiler isn't complaining

After reading this question today and having made the same mistake in the past, I wondered if it is required (because of the default convention?) That we MUST suffix "Controller" to the class name obtained from a class Controller

in ASP.NET MVC, why the compiler doesn't complain at all? At least a warning would have saved time.

So the code below will not work:

public class Search : Controller
{
    // GET: /Search/
    public ActionResult List()
    {
        var model = new MyModel();
        return View(model);
    }
}

      

So my question is:

  • Can we change this agreement? Can I change the setting somewhere and make the suffix text 'MvcController' instead?
  • More important, what is the reason why the C # compiler is not complaining? He can't figure it out, or is it undesirable / illogical?

question and the answer does not answer both of my questions, so I think it is not an exact duplicate.

+3


source to share


2 answers


The question you are referring to indicates why the "Controller" suffix is ​​a standard convention, as described in Why do MVC controllers need to have a terminating "Controller" convention on their class name? :

Imagine you have a ProductController that is probably handling instances of the Product Application Model entity. Without a naming convention for controllers, we would have two types with the same name , so we would always need to provide namespaces to distinguish the two.

To answer your questions:

Can we change this convention, that is, I can change the setting somewhere and make the text suffix 'MvcController' instead?

Yes, by creating your own IControllerFactory. See Adding a Factory Controller to ASP MVC .



What is the reason why the C # compiler doesn't complain? He can't figure it out, or is it undesirable / illogical?

The naming convention is just an MVC construct. MVC is a framework that runs on top of .NET, nothing special about it.

The compiler cannot figure this out since there is no trivial way to expose runtime requirements that need to be checked at compile time, for example: "If a class inherits from System.Web.Mvc.Controller

or Microsoft.AspNet.Mvc.Controller

, its name must end in 'Controller', unless an uncontrolled ControllerFactory is registered in it, in In this case, use the conventions from the factory, no matter what they are. "

MVC relies on reflection to check types (and their names) at runtime. The C # compiler runs at compile time.

+5


source


Unless you are under MVC 6 you need to name your controllers like this

 public class NameController:Controller{}

      



controller should

  • be an open class
  • inherits from controller or base class that inherits from controller class
  • not abstract class
  • not subclass
  • be named in a word ending in "Controller"
0


source







All Articles