Table of Contents
这是Default.aspx页面
Home Backend Development C#.Net Tutorial Analyzing the implementation principles of Asp.Net routing system

Analyzing the implementation principles of Asp.Net routing system

Feb 20, 2017 pm 05:20 PM

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);
    }
  }
Copy after login

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 id="这是Default-aspx页面">这是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>
Copy after login

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/

Analyzing the implementation principles of Asp.Net routing system

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:

Analyzing the implementation principles of Asp.Net routing system

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:

Analyzing the implementation principles of Asp.Net routing system

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.

Analyzing the implementation principles of Asp.Net routing system

Through the Reflector tool, we can see:

Analyzing the implementation principles of Asp.Net routing system

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:

Analyzing the implementation principles of Asp.Net routing system

In this UrlRoutingModule, what routing-related operations are performed? Let’s continue to look at the source code:

Analyzing the implementation principles of Asp.Net routing system

Analyzing the implementation principles of Asp.Net routing system

Analyzing the implementation principles of Asp.Net routing system

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:

Analyzing the implementation principles of Asp.Net routing system

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:

Analyzing the implementation principles of Asp.Net routing system

Match method:

Analyzing the implementation principles of Asp.Net routing system

Analyzing the implementation principles of Asp.Net routing system

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the difference between char and unsigned char What is the difference between char and unsigned char Apr 03, 2025 pm 03:36 PM

char and unsigned char are two data types that store character data. The main difference is the way to deal with negative and positive numbers: value range: char signed (-128 to 127), and unsigned char unsigned (0 to 255). Negative number processing: char can store negative numbers, unsigned char cannot. Bit mode: char The highest bit represents the symbol, unsigned char Unsigned bit. Arithmetic operations: char and unsigned char are signed and unsigned types, and their arithmetic operations are different. Compatibility: char and unsigned char

How to use char array in C language How to use char array in C language Apr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

See all articles