MVC5 routing system mechanism detailed explanation

Source: Internet
Author: User

There is a difference between requesting an ASP. NET MVC Web site and the previous Web form, which provides a routing mechanism within the ASP. When IIS accepts a request, it first looks at whether a static resource (. Html,css,js, picture, etc.) is requested. This step is the same as the Web Form and MVC, if it is not the request is a dynamic page, will go to ASP. NET pipeline, MVC program request will walk by the system, will map to a controller corresponding action method, and the Web The form Request Dynamic page is to find an ASPX file that actually exists locally. The following is a detailed introduction to the mechanism of the Aps.net MVC5 routing system through an ASP. NET MVC5 project.

I. Understanding Global.asax.cs

When we create a aps.net MVC5 project, a Global.asax file is generated in the root directory of the project.

     Public class MvcApplication:System.Web.HttpApplication    {        protectedvoid  Application_Start ()        {            Arearegistration.registerallareas ();            Filterconfig.registerglobalfilters (globalfilters.filters);             // Registering Routing Rules             routeconfig.registerroutes (routetable.routes);            Bundleconfig.registerbundles (bundletable.bundles);         }    }

This Application_Start method will be automatically invoked at the site launch, where we see: Routeconfig.registerroutes (Routetable.routes); The framework registers our custom routing rules so that subsequent URLs can correspond to the specific action. Now let's look at what the RegisterRoutes method does.

     Public classRouteconfig { Public Static voidregisterroutes (routecollection routes) {routes. Ignoreroute ("{Resource}.axd/{*pathinfo}"); Routes. MapRoute (Name:"Default", URL:"{Controller}/{action}/{id}", defaults:New{controller ="Home", action ="Index", id =urlparameter.optional}); }    }

The above code is the VS automatically generated for you, with only one default rule defined.
1. Rule name: Default
2, the URL fragment: {controller}/{action}/{id}, respectively, there are three paragraphs, the first paragraph corresponds to the controller parameter, the paragraph is the action parameter, the third paragraph is the ID parameter
3, the default value of the URL segment: Controller is home,action to Index,id = urlparameter.optional indicates that the parameter is optional.
The reason we visit http://www.xx.com/URL URL can be returned correctly, because we set the default value of the URL segment, equivalent to access:
Http://www.xx.com/Home/Index

RegisterRoutes calls the Maproute method of RouteCollection, RouteCollection is a collection that inherits from Collection<routebase>

Iii. ASP. NET MVC default naming convention 1, controller naming convention

The Controller class must end with a controller, for example: Homecontroller,productcontroller. When we use HTML Heper to refer to a controller on the page, we only need to home,product the front, ASP. The defaultcontrollerfactory that comes with the MVC framework automatically adds the controller to the end and starts looking for the corresponding class based on that name. We created a new controller for the ASP. NET MVC project, and the files are automatically placed in the Controllers folder of the root directory, and we can see that there is a HomeController.cs at first. Of course you can also implement interface Icontrollerfactory, define your own controllerfactory to change the behavior of finding controller files. I will introduce later in the article.

2. View naming convention

The default view of ASP. NET MVC is placed under the views file of the root directory, and the rule is this:/views/controllername/actionname.cshtml. For example: HomeController's action name is the Index view corresponding file:/views/home/index.cshtml
Therefore, the location of the view file is determined by the name of the Controller and action. The benefit of adopting this naming convention is that when the action returns to the view, the MVC framework will find the default view file according to this Convention. For example, in the Productcontroller action method list is finally the code:
return View ();
will automatically go to the path,/views/product/find the file list.cshtml (or list.aspx if using the old view engine).
You can also specify the name of the view:
Return View ("~/views/product/list.cshtml")
Or
Return View ("Myotherview")

When the MVC framework looks for a specific default view file, if it is not found under/views/controllername/, it will be looked up under/views/shared, and if it is not found, it will be wrong: The view is not found.

Iv. URL Rule description for ASP.

At first we registered some routing rules in the Application_Start event of the website Routes.maproute, when there is a request coming, the MVC framework will use these routing rules to match, once found to meet the requirements to deal with the URL. For example, there is the following URL:
Http://mysite.com/Admin/Index
URLs can be divided into segments, except for host headers and URL query parameters, and the MVC framework uses/to separate URLs into segments.

            routes. MapRoute (                "Default",                "{Controller}/{action}/{id}  ",                new"Home""Index  ", id = urlparameter.optional}            );

The above indicates that the URL rule is:
{Controller}/{action}
This routing rule has two segments, the first one is the controller, and the second is the action. Declare the URL segment each part to be enclosed in {}, equivalent to a placeholder, which is a variable.
When a URL request arrives, the MVC routing system is responsible for matching it to a specific routing rule and extracting the value from each segment of the URL. This is said to be "a specific routing rule" because more than one routing rule may be registered, and the MVC routing system will match the one in the registration order until it is there.
By default, URL routing rules only match URLs with the same number of URL segments. As the following table:

Url URL segment
Http://mysite.com/Admin/Index Controller = Adminaction = Index
Http://mysite.com/Index/Admin Controller = Indexaction = Admin
Http://mysite.com/Apples/Oranges Controller = Applesaction = oranges
Http://mysite.com/Admin No match-the number of segments is not enough
Http://mysite.com/Admin/Index/Soccer No match-the number of segments is super
V. MVC creates a simple route rule

We have previously registered routing rules in the following way:

 Public Static void registerroutes (routecollection routes) {     routes. MapRoute ("myroute""{controller}/{action}");}

The Maproute method of RouteCollection was used. In fact, we can call the Add method and pass an instance of the route to the same effect as it does.

 Public Static void registerroutes (routecollection routes) {     new Route ("{controller}/{action} " New Mvcroutehandler ());    Routes. ADD ("myroute", Myroute);}
Vi. setting default values for MVC routes

Previously said: URL routing rules only match with it has the same URL segment number of URLs, this is strict, but we want to some paragraphs do not enter, let the user into the specified page. Like, http://www.xx.com/Home/is entering the Home index. You only need to set the default values for the MVC route.

 Public Static void registerroutes (routecollection routes) {    routes. MapRoute ("myroute""{controller}/{action}"New  "Index"  });  

The default value for the Controller and action to set.

 Public Static void registerroutes (routecollection routes) {routes. MapRoute ("myroute""{controller}/{action}",         New " Home " " Index "

The following is a specific URL corresponding to the route map.

Number of URL segments Instance Route Map
0 mydomain.com Controller = Homeaction = Index
1 Mydomain.com/customer Controller = Customeraction = Index
2 Mydomain.com/customer/list Controller = Customeraction = List
3 Mydomain.com/customer/list/all No match-url segment too much

VII. MVC uses static URL segments

The previous definition of a routing rule is a placeholder form, {controller}/{action}, which we can also use when using static strings. Such as:

 Public Static voidregisterroutes (routecollection routes) {routes. MapRoute ("Myroute","{controller}/{action}",        New{controller ="Home", action ="Index" }); Routes. MapRoute ("","Public/{controller}/{action}",       New{controller ="Home", action ="Index" });}

Matches above: Http://mydomain.com/Public/Home/Index

Route: "Public/{controller}/{action}" matches only three segments of the URL, the first paragraph must be public, the second and third can be any value, respectively, for the Controller and action. In addition to this, a routing rule can contain both static and variable mixed URL segments, such as:
 Public Static voidregisterroutes (routecollection routes) {routes. MapRoute ("Myroute","{controller}/{action}",        New{controller ="Home", action ="Index" }); Routes. MapRoute ("","Public/{controller}/{action}",       New{controller ="Home", action ="Index" }); } 

Viii. custom parameter variables in the route of MVC

The MVC framework can define its own variables in addition to the parameters of its own controller and action. As follows:

 Public Static voidregisterroutes (routecollection routes) {routes. MapRoute ("Myroute","{Controller}/{action}/{id}",        New{controller ="Home", action ="Index", id ="1" });} 

id=urlparameter.optional setting URL Parameters optional

The MVC framework obtains from the URL the value of the variable can be accessed through routedata.values["XX"], this collection.

IX. MVC defines the constraints of routing rules

In the previous we described setting route defaults and optional parameters for the rules for MVC routing, and now let's go a little deeper and we'll constrain the routing rules.

1. Restricting ASP. NET MVC routing rules with regular expressions

 Public Static voidregisterroutes (routecollection routes) {routes. MapRoute ("Myroute","{Controller}/{action}/{id}/{*catchall}",        New{controller ="Home", action ="Index", id =urlparameter.optional},New{controller ="^h.*"},        New[] {"urlsandroutes.controllers"});}

The above uses a regular expression to limit the ASP. NET MVC routing rule, which means that only URLs with the Contorller name beginning with H are matched.

2. Limit the ASP. NET MVC routing rule to a specific value

 Public Static voidregisterroutes (routecollection routes) {routes. MapRoute ("Myroute","{Controller}/{action}/{id}/{*catchall}",        New{controller ="Home", action ="Index", id =urlparameter.optional},New{controller ="^h.*", action ="^index$|^about$"},        New[] {"urlsandroutes.controllers"});} 

The above example defines a constraint on both the controller and the action, and the constraint is both effective and satisfying. The above indicates that only URLs with the Contorller name beginning with H are matched, and the action variable has a value of index or a URL of about.

3. Limit the ASP. NET MVC routing rule to submit request mode (POST, GET)

 Public Static voidregisterroutes (routecollection routes) {routes. MapRoute ("Myroute","{Controller}/{action}/{id}/{*catchall}",        New{controller ="Home", action ="Index", id =urlparameter.optional},New{controller ="^h.*", action ="index| about", HttpMethod=NewHttpmethodconstraint ("GET") },        New[] {"urlsandroutes.controllers" });}

MVC5 routing system mechanism detailed explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.