I. URL routing
1.1 Comparison to HTTP requests via browser
When a client makes a request to an ASP. NET Web site, it can find the appropriate HttpHandler to handle the Web page through R even Tony Lid, the approximate process
If HttpHandler is handled by Mvchandler, then it enters the MVC execution life cycle, finds the appropriate controller and action to process it, and feeds the information back to the client.
1.2 Return the appropriate URLs to the browser
Another use of URL routing is to determine what URL mvc should output and return it to the browser, or to refer to the definition of a URL route in order to dynamically determine what the MVC output URL should be if it is to jump to an address or display a hyperlink in a view.
1.3 Default URL Routing
Global.asax has defined two default URL routes, as shown in the image below:
① All the entries that are performed by the ASP. NET Web application are HttpApplication Application_Start () events, and all MVC routing will be defined here. Where Routtable.routes is a public static object that stores all routing rule sets (RouteCollection classes).
The Ignoreroute () helper method in the ② default RegisterRoutes () method is used to define URLs that do not need to be processed by routing.
③ "{resource}" represents a route Valueg expression named "Resource", but in fact it can be any name, it just represents a variable space (placeholder class), in short, represents a location, Used to place a variable that cannot be used.
④ "{*pathinfo}" represents a RouteValue expression called "PathInfo", and the asterisk (*) in front of the name means "catchall" (Catch All). The value of this routevalue expression named "PathInfo" is the complete path information (path info) that is deducted from the remaining URLs in the ③ . For example: The URL is "/TEST.AXD/A/B/C/D", the value of "{PathInfo}" is "A/B/C/D", and if no asterisk is added, the value of "{PathInfo}" should be "a". You can actually take any name here, because it represents only the position of a variable.
⑤ MapRoute () is the most commonly used helper method for defining routing rules.
⑥ defines the name of the route, which is "Default".
⑦ defines the URL format and the RouteValue expression name for each URL paragraph (pathsegment).
TIP: The URL cannot start with a slash (/).
⑧ defines the default values for each RouteValue expression, which is replaced by the default when the URL route is less than the HTTP request URL.
Second, how the URL of the HTTP request corresponds to the URL route
Since two URL routes are defined by default, according to the rules of the ASP. NET routing, when HTTP requests, the URL will be a comparison of URL routing, and it is up and down a pair, until compared to the URL to meet the HTTP request.
2.1 URL Routing Example
Here's an example of a more conceptual connection between URLs and routing.
[1]. http://localhost/Trace.axd/a/b/c/d/e
TIP: all URLs start with "http://localhost/"!
(1) Compare the routes. The "{resource}.axd/{*pathinfo}" URL format for the Ignoreroute namespace.
(2) "{Resource}.axd" is compared to "trace.axd", so it continues to be compared to the next RouteValue expression.
(3) Compare "{*pathinfo}" and get "a/b/c/d/e".
(4) Because all RouteValue expressions are successful, the HTTP request is serviced by this URL route.
The URL uses routes. The Ignoreroute namespace is processed, that is, MVC ignores this request and instead continues processing with the ASP.
[2] Http://localhost/Trade.axd
(1) Compare the routes. The "{resource}.axd/{*pathinfo}" URL format for the Ignoreroute namespace.
(2) "{Resource}.axd" is compared to "trace.axd", so it continues to be compared to the next RouteValue expression.
(3) compared to "{*pathinfo}", because the requested part already has no data, so theoretically no more than to any result. However, because "{*pathinfo}" belongs to Callall, this syntax is compared to the entire contents including the empty string, so this part is also a success, but "{*pathinfo}" is empty.
(4) Because all RouteValue expressions are successful, the HTTP request is serviced by this URL route.
The URL uses routes. The Ignoreroute namespace is processed, that is, MVC ignores this request and instead continues processing with the ASP.
[3] Http://localhost/Member/Detail?id=123
(1) Compare the routes. The "{resource}.axd/{*pathinfo}" URL format for the Ignoreroute namespace.
(2) A portion of the URL to the request, i.e. "Member", because there is no comparison to ". Axd", so the comparison fails.
(3) Jump to routes. The "{controller}/{action}/{id}" URL format for the Maproute namespace.
(4) compared to the first part of the request URL, which is "Member", and is compared to the {controller} parameter.
(5) The second part of the request URL, which is "Detail", and is compared to the "{action}" parameter.
(6) The next "id=123" is not part of the URL, so it will not be counted into the routevalue expression, so it will not be in the right way.
(7) The "{ID}" section reads the default value, which is the "urlparameter.optional" section because there is no comparison. Because of the default value, it is also a success.
(8) Because all RouteValue expressions are successful, the HTTP request is serviced by this URL route.
The URL uses routes. Maproute the namespace for processing, and mvchandler the value to the appropriate controller and action program. This will correspond to the detail action of the Membercontroller.
TIP: All routing parameters that appear in the URL and parameters location are necessary parameters that must be fully compliant with the required read rule to be successful, and if the comparison fails, it will be tuned to the next URL routing rule.
2.2 Adding restrictions to URL routing
MapRoute () is the most commonly used helper method for defining routing rules, and it has many ways of applying (overloading). A common application is "style alignment rules (regular expressions) + constraints."
1 context. MapRoute (2 3 "Order_default", 4 "Order/{controller}/{action}/{id}", 5 new {action = "Index", id = Urlparameter.optional},6 New {id = @ "\d+"}7 );
We set up 4 parameters in the Maproute () helper method, which specifies an anonymous object whose id attribute is our constraint over the {ID} route value, which is represented by a regular expression (Regular expression). The "\id+" represents a successful comparison to the {ID} route value that must be a number, which is the limit.
If the URL is "Http://localhost/Order/Member/Index/123ABC.", because this pair to the {ID} route value does not meet the restrictions, so this URL even if compared to the failure, then will automatically skip to the next URL routing rules continue to match.
TIP: The regular expression defined here is exactly the same as the default. If you define a style of "\id+", in fact, it will be converted to "^\d+$" when compared.
Iii. How URL routing generates URLs in MVC.
A URL is a function of URL routing over URL routing, and another key feature is to generate the appropriate URLs in the controller or view based on the definition of the URL route. Here's how to get a dynamic URL using the RouteTable.Routes.GetVirtualPath namespace.
Test with the default MVC Project module first. Open URL http://localhost/Home/About, the resulting route value for this request
Field |
Value |
Controller |
Home |
Action |
About |
Id |
Urlparameter.optional |
Add the following program code to the "/views/home/about.aspx" page.
1 <%=2 RouteTable.Routes.GetVirtualPath (3 request.requestcontext,4 new RouteValueDictionary ( New {page=1}) 5 ). VirtualPath 6 %>
You can see that in the RouteTable.Routes.GetVirtualPath namespace, the first parameter is Request.requestcontext, and the current request information is entered, including RouteValue, QueryString and other complete requests; The second parameter has more than one RouteValueDictionary object entered, and a {page} route value is inserted. Therefore, a set of route values is merged before the URL route is fetched, as shown in the table:
Field |
Value |
Action |
About |
Id |
Urlparameter.optional |
Page |
1 |
Finally, MVC uses this set of new route values from top to bottom-more than all routing rules in the route table (routetable), which has the most appropriate routing rules and produces the appropriate URLs.
With the following routing rule, where 3 route parameters are defined, and 3 of the 4 route values we get are fully defined, this URL route is selected, and MVC generates URLs in a format that is well-defined for this route.
1 routes. MapRoute (2 "Default", //route name 3 "{controller}/{action}/{id}", //URL with parameter 4 new 5 { // Parameter default value 6 controller = "Home", 7 action = "Index", 8 id = urlparameter.optional 9 }10 );
Because the {page} parameter is not one of the URL routing parameters, the new {page} parameter is replaced with the QueryString parameter, and the output is as follows.
/home/about?page=1
Let me give you a more complicated example. The first routing rule is defined as follows:
1 routes. MapRoute (2 "Member", //route name 3 "Member/{action}/{page}", //URL with parameter 4 new //parameter default value 5 {6 controller = "Membercenter", 7 action = "List" 8 }, 9 new10 {One action = @ "index| List| Detail ", page = @" \d+ " }14 ); MapRoute ( "Default",/ /route name " {controller}/{action}/{id}",/ /URL18 with parameters new19 { //parameter default value -controller = "Home", action = "Index", the id = urlparameter.optional23 } );
Add the following program code to the "/views/home/about.aspx" page.
1 <%= 2 RouteTable.Routes.GetVirtualPath (3 request.requestcontext, 4 new RouteValueDictionary ( New { 5 controller = "Membercenter", 6 action= "Detail" 7 }) 8 ). VirtualPath 9 %>
Replace "controller" with "Membercenter" in the 2nd parameter and replace "action" with "Detail", so a new set of route values, such as tables, will be merged before the URL is obtained:
Field |
Value |
Controller |
Membercenter |
Action |
Detail |
Id |
Urlparameter.optional |
MVC uses this set of new route values to get the most appropriate routing rules from the top to bottom of all route rules in the routing table. When this compares to the first rule, because there are already two route parameters defined, namely "{action}" and "{page}", and only "action" in our routing table does not have "page", the default {page} parameter in the parameter default value is checked, and the result is not. So the comparison fails. MVC does not generate URLs for this URL, and then jumps to the next URL route for comparison. Finally, the result of the comparison is "/membercenter/detail".
Modify the "/views/home/about.aspx" page of the program code, add the "page" parameter, the example is as follows:
1 <%= 2 RouteTable.Routes.GetVirtualPath (3 request.requestcontext, 4 new RouteValueDictionary ( New { 5 controller = "Membercenter", 6 action = "Detail", 7 page = "TEST" 8 }) 9 ). VirtualPath10 %>
When you do this, a new set of route values (RouteValue) is merged, such as tables:
Field |
Value |
Controller |
Membercenter |
Action |
Detail |
Id |
Urlparameter.optional |
Page |
TEST |
When we compare to the first rule, because we have defined two route parameters, namely {action} and {page}, and our routing table already has the route value of "Action" and "page", the necessary parameters have all been met, so it will be further compared with the restriction criteria.
Because the {page} parameter has been defined with a constraint of "@" \d+ "", but the page value in the route value is "TEST", the comparison fails because the restriction fails. Therefore, MVC does not use this URL route to generate URLs, and then jump to the next URL to route the comparison.
Finally, the result is "/membercenter/detail?page=test".
Summary: Using the RouteTable.Routes.GetVirtualPath namespace to generate URLs will generally use the following criteria.
- If you bring the 1th parameter into the Request.requestcontext namespace, all current route values are pre-acquired. You can also enter "null" to indicate that there is no default route value.
- Using all the route values that are currently merged with the URL route table is compared to all the necessary parameters. If the comparison succeeds, further checks are made to see if the restrictions are met.
- If the necessary parameters are not found, the parameter defaults are found, and if they are still not found, the comparison fails.
- If the above-mentioned success is successful, the RouteTable.Routes.GetVirtualPath namespace will generate the URL using the URL defined by the URL route.
The RouteTable.Routes.GetVirtualPath namespace generates a complete flowchart of URLs.
Iv. life cycle of MVC execution
The implementation life cycle of MVC is broadly divided into 3 stages, namely:
(1) URL routing comparison;
(2) Execute Controller and action;
(3) Execute the view and return the result.
4.1 URL Routing Alignment
When IIS receives an HTTP request, it first handles all the operations related to URL routing through urlroutingmodule. By default, if a URL can correspond to an entity file at the root of the URL, it will not be processed through MVC, but instead be directly executed by IIS or ASP.
If the URL is "Http://localhostContent/Site.css", because there is a "content" directory in the root directory of the site, and "content" There are also site.css files in the directory, and all MVC does not parse this URL into content controllers and site.css actions.
Another example of. NET Web forms, the URL is "http://localhost/Member/Login.aspx", create a special URL route in the Global.asax file, as follows.
1 routes. MapRoute (2 "default_aspx", //route name 3 "{controller}/{action.aspx}/{id}", //URL with parameter 4 new 5 { //parameter default value 6 controller = "Home", 7 action = "Index", 8 id = urlparameter.optional 9 } (Ten );
In this case, if there are "/member/login.aspx" programs written using. NET Web Forms in the root directory of the Web site, MVC does not apply urlrouting, but instead gives control of the process to IIS and is executed by IIS in the next module. In this case, the "/member/login.aspx" program is executed.
If the "/member/login.aspx" program does not exist, then the MVC routing will formally start the comparison, and in comparison to the above URL, will perform the Membercontroller Login action.
If you set the Routetableroutes.routeexistingfiles parameter value to "true" at the front of the Application_Start () event of the Global.asax file, MVC's urlrouting will not first determine if there is an entity file exists, the program code is as follows:
1 protected void Application_Start () 2 {3 RouteTable.Routes.RouteExistingFiles = true;4 Arearegistration.registerallareas (); 5 6 registerroutes (routetable.routes); 7 }
Once set, the Web site receives HTTP requests that are compared using the URL routing rules defined in the RegisterRoutes () method. If the comparison succeeds, it is treated with MVC, otherwise, the executed rights are returned to IIS.
Note: if the Ignoreroute () helper method succeeds in MVC, it causes the program to jump directly out of the MVC execution life cycle, returning the right to the execution of the program to IIS. by which module (model) or which process history (Handler) the IIS feels next.
When using the URL routing rules defined by the RegisterRoutes () method, in fact, after the success of the comparison, the default value is determined by Mvcroutehandler to send the HTTP request to which HttpHandler to execute. MVC defaults to handing the HTTP request to Mvchandler for execution.
The Mvcroutehandler program code shown in the figure shows that to customize the Routehandler, as long as the Iroutehandler interface class is developed by itself, A custom Routehandler can be adopted to determine which httphandker the URL routed through the URL should be given to. Therefore, you can use custom Routehandler and HttpHandler to provide accessibility to your MVC site.
4.2 Execute controller and Action 4.3 execute view and return results
When the program executes to Mvchandler, the HttpHandler entry is the ProcessRequest () method.
MVC note URL Routing and MVC life cycle