Asp. NET routing system: separation of URLs from physical files "go"

Source: Internet
Author: User

The URL routing system, which behaves as a dynamically mapped request address with the target controller and action, is not specifically owned by ASP. NET MVC, but is built directly into ASP. Asp. NET realizes the separation of the request address and the physical file through the URL routing system. [Source code address download from here]

I. Separation of URLs from physical files

For an ASP. NET Web form application, any request corresponds to a specific physical file. The physical files deployed on the Web server can be static (slices and static HTML files, etc.) or dynamic (such as. asxp files). For static file requests, ASP. NET returns the entire contents of the file directly, while a request for a dynamic file triggers execution of the relevant code and ultimately returns the result after execution. But this way of tightly binding URLs to physical files is not a good solution, and its limitations are mainly reflected in the following areas:

    • Flexibility: because the URL is a reflection of the physical file path, it means that if the path to the physical file changes (such as changing the directory structure or file name), the link will become invalid based on that file.
    • readability: In many cases, URLs need not only access to the correct network resources, but also good readability, and the best URLs should give us a glimpse of what the target resource is for it to access. The tight binding of the request address to the physical file allows us to completely lose the opportunity to define a highly readable URL.
    • SEO optimization: for Web site development, in order to meet the search engine retrieval rules, we need to design the URL effectively so that it can be easily indexed by the main engine retrieval. If the URL is completely associated with a physical address, this is tantamount to losing the ability to optimize SEO.

Because of the limitations of URL and physical file binding mechanism, we need a more flexible mechanism to separate the request address of the physical file from the path of the file itself, and implement the relationship between the URL and the physical file through a dynamic mapping mechanism.

When it comes to this, many people might think of URL rewriting. Microsoft has written a URL rewrite module for IIS 7 in order for the Web app to independently address the URLs used to access the app's resources. This is a rule-based URL rewrite engine that changes the URL of the request before the URL is processed by the Web server. For dynamic Web applications, it can provide users and search engines with friendly Url,url overrides and redirects based on HTTP headers and server variables, and can access control over the site's content.

URL rewriting resolves the separation of URLs from physical addresses at the IIS level, which is registered with a local (Native) code-based module on the pipeline for HTTP request processing by IIS, so it can be applied to Web applications that are hosted in IIS. The URL routing system is part of the ASP, and is implemented through managed code. To give readers a sense of the perception of ASP. NET URL routing, let's demonstrate a simple example.

Ii. Example Demo: Mapping a request address to an. aspx page through URL routing

Next we will create a simple ASP. NET Web Forms application and use a URL independent of the path of the. aspx file to access the corresponding Web page, and the mapping between the two is implemented by URL routing. We are a scenario for employee management, and we will create a page that shows the list of employees and the details of an employee, as shown in the page rendering effect.

We will focus on the URLs of the two pages shown. The page address to display the employee list is http://localhost:2738/employees. When a user taps a connection that appears as a name, the page used to display the details of the selected employee is rendered and the URL pattern for the page address is http://localhost:2738/employees/{name}/{id}. For the latter, the end user can see from the URL which employee's information is obtained from that address. One might ask, why should we include the employee's name and ID in the URL? This is because the ID (in this case, the GUID) is less readable than the employee's name, but the employee name is not unique, and the ID we use here is the unique identity provided for the need for logical processing, and the name is for readability.

We define all employee information (ID, name, gender, date of birth, and department) as shown in the employee type. As a routine, we define the following Employeerepository type represents the domain model for maintaining the employee list. The list of employees maintained is represented by a static field employees. Employeerepository's GetEmployees method returns the list of employees that contain the appropriate employee, based on the specified ID, and returns all employee lists if the specified ID is "*"

  Public classEmployee { Public stringId {Get;Private Set; }  Public stringName {Get;Private Set; }  Public stringGender {Get;Private Set; }  PublicDateTime BirthDate {Get;Private Set; }  Public stringDepartment {Get;Private Set; }  PublicEmployee (stringIdstringNamestringGender, DateTime BirthDate,stringDepartment) {          This. Id =ID;  This. Name =name;  This. Gender =gender;  This. BirthDate =birthDate;  This. Department =Department; } }  Public classEmployeerepository {Private StaticIlist<employee>employees; StaticEmployeerepository () {Employees=NewList<employee>(); Employees. ADD (NewEmployee (Guid.NewGuid (). ToString (),"Zhang San","male",NewDateTime (1981,8, -),"Sales Department")); Employees. ADD (NewEmployee (Guid.NewGuid (). ToString (),"John Doe","female",NewDateTime (1982,7,Ten),"Personnel")); Employees. ADD (NewEmployee (Guid.NewGuid (). ToString (),"Harry","male",NewDateTime (1981,9, +),"Personnel")); }      PublicIenumerable<employee> GetEmployees (stringID ="")     {         returnEmployees. Where (E = e.id = = Id | |string. IsNullOrEmpty (ID) | | id=="*"); } }

For the two pages shown, it actually corresponds to the same. aspx file, which is the Default.aspx of the Web app's default page. To access the. aspx page through a URL that is independent of the physical path, we need to use a URL routing mechanism to implement the mapping between the two. For this we have written the following lines of code in the added Global.asax file. As shown in the following code snippet, the Application_ In the Start method we get the System.Web.Routing.RouteCollection object that represents the list of routed objects through the routes property of System.Web.Routing.RouteTable, and call the Mappageroute side of the list object The Default.aspx page (~/default.aspx) is mapped to a URL template (employees/{name}/{id).

  Public classGlobal:System.Web.HttpApplication {protected voidApplication_Start (Objectsender, EventArgs e) {         varDefaults =Newroutevaluedictionary{{"name","*"},{"ID","*"}}; RouteTable.Routes.MapPageRoute ("","Employees/{name}/{id}","~/default.aspx",true, defaults); } }

The RouteValueDictionary object that is the last parameter of the Mappageroute method is used to specify the default value defined in the corresponding variable ({name} and {ID}) in the routing template. For a Routing object that specifies a default value, if the subsequent part of the current request address is missing, it fills the address with the provided default value before the pattern is matched. In the code snippet shown above, we specify the default value for both {name} and {ID} variables as "*". For requests with URI Http://localhost:2738/employees, our registered route objects will be formatted as http://localhost:2738/employees/*/*. The latter is undoubtedly matched with the pattern of the defined URL pattern being turned out.

In the Default.aspx page, we use GridView and DetailsView respectively to display the details of all employee lists and a list, and the following code snippet represents the HTML for the body part of the page. It is worth mentioning that the HyperLinkField connection that appears in the GridView template as the employee's name takes the pattern we defined in the URL template (employees/{name}/{id) above.

<formID= "Form1"runat= "Server">    <DivID= "page">            <Asp:gridviewID= "Gridviewemployees"runat= "Server"AutoGenerateColumns= "false"Width= "100%">            <Columns>                <Asp:hyperlinkfieldHeaderText= "Name"DataTextField= "Name"DataNavigateUrlFields= "Name,id"datanavigateurlformatstring= "~/employees/{0}/{1}" />                <Asp:boundfieldDataField= "Gender"HeaderText= "Gender" />                <Asp:boundfieldDataField= "BirthDate"HeaderText= "Date of birth"dataformatstring= "{0:dd/mm/yyyy}" />                <Asp:boundfieldDataField= "Department"HeaderText= "department" />            </Columns>        </Asp:gridview>        <Asp:detailsviewID= "Detailsviewemployee"runat= "Server"autogeneraterows= "false"Width= "100%">            < Fields>                <Asp:boundfieldDataField= "ID"HeaderText= "ID"  />                <Asp:boundfieldDataField= "Name"HeaderText= "Name"  />                <Asp:boundfieldDataField= "Gender"HeaderText= "Gender" />                <Asp:boundfieldDataField= "BirthDate"HeaderText= "Date of birth"dataformatstring= "{0:dd/mm/yyyy}" />                <Asp:boundfieldDataField= "Department"HeaderText= "department" />            </ Fields>        </Asp:detailsview>    </Div></form>

The entire background code for the Default.aspx page is defined as follows. Since all employee lists and the details of a single employee are reflected in this page, we need to determine what data should be rendered based on their request address, which can be achieved through the routing data represented by the Routedata property. The page has a routedata of type System.Web.Routing.RouteData that represents the route data that is generated by resolving the request address through a registered routing object that matches the current request. The values property of Routedata is a dictionary that stores the route variables whose key is the variable name. In the code snippet shown below, we get the route variable (routedata.values["id") that represents the employee ID, and if it is the default, it means that the current request is for the employee list, and vice versa, for the specific employee specified.

  Public Partial classdefault:page{Privateemployeerepository repository;  Publicemployeerepository Repository {Get{return NULL= = Repository? Repository =Newemployeerepository (): repository;} }    protected voidPage_Load (Objectsender, EventArgs e) {                   if( This. IsPostBack) {return; }        stringEmployeeId = This. routedata.values["ID"] as string; if(EmployeeId = ="*"||string. IsNullOrEmpty (employeeId)) { This. Gridviewemployees.datasource = This.            Repository.getemployees ();  This.            Gridviewemployees.databind ();  This. Detailsviewemployee.visible =false; }        Else        {            varEmployees = This.                           Repository.getemployees (EMPLOYEEID);  This. Detailsviewemployee.datasource =employees;  This.            Detailsviewemployee.databind ();  This. Gridviewemployees.visible =false; }    }        }

Transferred from: www.cnblogs.com/artech/archive/2012/03/19/aspnet-routing-01.html

Asp. NET routing system: separation of URLs from physical files "go"

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.