Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the controllers on ASP.NET MVC name-based?

In ASP.NET MVC, we're required to use the suffix "Controller" for all controllers. This seems unnecessarily restrictive - is there a technical reason for it?

I'm mostly just curious, but can see situations where more flexible naming rules could improve code organization. Couldn't the discovery of possible controller classes be easily made using reflection to search for Controller derived classes? Or require that controller classes be marked with a ControllerAttribute?

like image 559
Edwin Jarvis Avatar asked Nov 05 '08 18:11

Edwin Jarvis


People also ask

What must the controller be named in ASP.NET MVC?

In ASP.NET MVC, every controller class name must end with a word "Controller". For example, the home page controller name must be HomeController , and for the student page, it must be the StudentController . Also, every controller class must be located in the Controller folder of the MVC folder structure.

What is the purpose of the controller in ASP.NET MVC?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

How controller is defined in MVC?

Step 1 − Create an MVC Empty Application and then right-click on the Controller folder in your MVC application. Step 2 − Select the menu option Add → Controller. After selection, the Add Controller dialog is displayed. Name the Controller as DemoController.

Which is the base interface for Controllers in ASP.NET MVC?

ASP MVC requires that all controllers implement IController interface. A controller doesn't need to derive from Controller or ControllerBase class. You can find an example of a custom controller implementing the IController interface in Adam Freeman's book.


2 Answers

The MVC community is heavily influenced by Ruby on Rails, which values "convention over configuration". By just naming things consistently, the application can run with zero configuration.

like image 108
Jacob Carpenter Avatar answered Oct 20 '22 15:10

Jacob Carpenter


One of the benefits of this convention is that it's common to have a URL segment, controller, and a model class all have the same name.

URL: /product/ Controller: Product : Controller Model: Product

This would cause a naming conflict. So we made a convention to have controller names suffixed with "Controller" to avoid this conflict. However, you can override this behavior via our extensibility APIs.

like image 38
Haacked Avatar answered Oct 20 '22 14:10

Haacked