Home > Article > Backend Development > Analyzing the implementation principles of Asp.Net routing system
For Asp.Net Web Forms applications, the requested Url corresponds to a specific physical file (http://xxx.com/default.aspx). Such Url is closely bound to the specific physical file, which brings many convenient limitations: readability, SEO optimization, etc. To address these limitations, Microsoft introduced a URL routing system. Let's analyze the Asp.Net routing system through a Demo.
Create an empty WebForm application and add the following code to the Global.asax.cs file:
public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { //处理匹配的文件 RouteTable.Routes.RouteExistingFiles = true; //url默认值 RouteValueDictionary defaults = new RouteValueDictionary() { { "name", "wuwenmao" }, { "id", "001" } }; //路由约束 RouteValueDictionary constraints = new RouteValueDictionary() { { "name", @"\w{2,10}" }, { "id", @"\d{3}" } }; //与路由相关的值,但不参与路由是否匹配URL模式 RouteValueDictionary dataTokens = new RouteValueDictionary() { { "defaultName", "wuwenmao" }, { "defaultId", "001" } }; RouteTable.Routes.MapPageRoute("default", "employees/{name}/{id}", "~/Default.aspx", false, defaults, constraints, dataTokens); } }
Create a new file named Default WebForm page, the page code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication2.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <h1>这是Default.aspx页面</h1> <p> RouteData中Values: <ul> <% foreach (var value in RouteData.Values) { %> <li> <%=value.Key %>=<%=value.Value %> </li> <%} %> </ul> RouteData中DataTokens: <ul> <% foreach (var value in RouteData.DataTokens) { %> <li> <%=value.Key %>=<%=value.Value %> </li> <%} %> </ul> </p> </form> </body> </html>
The input paths are the following three, and the results are the same:
http:/ /localhost:2947/employees/wuwenmao/001
http://localhost:2947/employees/wuwenmao
http://localhost:2947/employees/
The reason is that when registering the route, default values are set for the variables in the routing template, so the above three URLs are equivalent when using them.
Looking back at the Global file, a variable is also set when registering the route:
This is to use regular rules to limit the value of the variable in the routing template. , the corresponding variable value in the request URL can only be requested correctly if it matches the regular expression, otherwise a 404 error will be returned. If the length of the id value is greater than 3:
The above has experienced the Asp.Net routing system through a simple example. Let's analyze the Asp.Net by looking at the source code. The implementation principle of routing system.
First of all, when we use the following statement to register a route in our Global file, we actually add a route to the global routing table.
Through the Reflector tool, we can see:
Now there is a problem. After registering the route, How does Asp.Net use the routing system? In fact, the Asp.Net routing system registers an HttpModule object, which intercepts the request, and then dynamically maps it to the HttpHandler object used to process the current request, and finally processes and responds to the request through the HttpHandler object. This HttpModule is actually UrlRoutingModule. When we start the Asp.Net program, we can verify it through the Modules attribute in the Global file. As you can see from the screenshot below, the Modules attribute contains the registered HttpModule, which contains UrlRoutingModule:
In this UrlRoutingModule, what routing-related operations are performed? Let’s continue to look at the source code:
Viewing the source code above, we can see that when a request comes, Asp.Net intercepts the request through the registered UrlRoutingModule module, and then Find the matching RouteData from the global routing table. If found, obtain the corresponding HttpHandler according to HttpApplication, and then map it to the current request context for subsequent pipeline events to process the current request.
Let's continue to look at the source code and analyze how UrlRoutingModule obtains RouteData from the global routing table:
As you can see from the above, calling GetRouteData of the global routing table in UrlRoutingModule actually calls GetRouteData of each registered Route in turn, returning the first matching RouteData. If registered None of the routes match, and null is returned.
Let’s take a look at what GetRouteData in Route does:
Match method:
By calling the GetRouteData method of Route in sequence, the following operations are done in the GetRouteData method:
1. The Match method of the ParsedRoute type is called to request the Url and register it in Matching of the routing template in the current Route object. If there is no match, null is returned directly;
2. If the request Url matches the routing template of the current Route object, a common RouteData object;
3. Check whether the current request Url passes according to the constraints defined when registering routing information. If not, return null;
4. Assign values to the Values and DataTokens of the RouteData object;
5. Return the RouteData object;
At this point, the analysis of the Asp.Net routing system has basically been completed, and there are still many details that cannot be analyzed one by one due to space limitations.
Summary:
Through the above analysis, let us sort out our ideas and summarize the work done by the Asp.Net routing system: First, we registered the Route object in Global, and then Intercept the request Url through the HttpModule module UrlRoutingModule registered in Asp.Net, and then call GetRouteData of the Route object from the global routing table RouteTables.Routes to match the request Url and the registered routing information, return the first matching RouteData, and the search is completed If there is no match after the entire RouteTables.Routes, null will be returned, and 404 will eventually be returned to the front-end page.
The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.
For more articles analyzing the implementation principles of Asp.Net routing system, please pay attention to the PHP Chinese website!