How does ASP.NET MVC dynamically create controllers and views?

This is a point of curiosity, not the actual problem I am facing: how does ASP.NET MVC create the appropriate controller and view objects from the string name in the RouteCollection? I tried to search in real ASP.NET MVC2 code to figure this out, but get lost in the factory controller class.

When I register my routes, I map the first block to the controller, the second to the action, the third to the identifier, but how does the program accept line names and create new objects?

/Users/Update/15354 = New UserController, executes Update() - how? 

The only thing I can imagine is to reflect all the classes in the project and create one that matches the requested name, but then how would you resolve the conflict in the class names without knowing which namespace to use?

+4
source share
1 answer

The standard FooController naming convention dictates that all controllers must have the suffix "Controller"; this way, when your current route points to the controller "Foo", ASP.NET MVC checks the types inside your application that inherit from Controller and look for a name whose name matches "Foo" + "Controller".

You are right in believing that ASP.NET MVC uses reflection to find the right controller, but this is a relatively small impact, since reflection data is cached by the application during its initial launch.

If you have two controllers with the same name and different namespaces, you can use the alternative MapRoute () form to indicate which controller you are going to allow.

 routes.MapRoute( "Error_ServiceUnavailable", "error/service-unavailable", new { controller = "Error", action = "ServiceUnavailable" }, new[] { "Controllers" } ); routes.MapRoute( "Admin_Error_ServiceUnavailable", "admin/error/service-unavailable", new { controller = "Error", action = "ServiceUnavailable" }, new[] { "Areas.Admin.Controllers" } ); 
+4
source

Source: https://habr.com/ru/post/1341878/


All Articles