Use ASP. NET web form Routing

Source: Internet
Author: User
Use ASP. NET web form routing Scott Allen code download location: msdn code base
What is a route in the online browsing code directory?
Brief history of URL rewriting
Route and route handling program
Configure routes for ASP. NET
Configure routes
Solution route Handler
Routing and security
URL generation
Route Summary

Microsoft. NET Framework 3.5 Service Pack 1 introduces a routing engine during ASP. NET runtime. The routing engine can separate the URLs in the request from the actual web forms that are passed in the HTTP request in response, so that you can build a friendly URL for the Web application. Although ASP. NET has always been able to use friendly URLs in earlier versions, the routing engine provides a simpler, clearer, and easier way to test. The routing engine was initially part of the ASP. NET Model View Controller (MVC) framework and is still in the preview phase when writing this article. However, Microsoft encapsulates the routing logic in the system. Web. Routing assembly and releases the Assembly along with SP1. Currently, this Assembly uses ASP. the net Dynamic Data feature (which is also released with SP1) provides routes for websites. However, in this column, I will introduce how to use ASP. net web form to use the routing function.

What is a route? Assume that you have an ASP. NET web form named recipedisplay. aspx, which is located in a folder named web forms. When using this web form viewing scheme, the traditional method is to build a URL pointing to the actual location of the form, and embed some data into the query string by encoding, to inform the web form of the solution to be displayed. The end of such a URL may be as follows:/webforms/recipedisplay. aspx? Id = 5, where number 5 represents the primary key value in a database table filled with solutions. In essence, a route divides a URL endpoint into multiple parameters and uses these parameters to route HTTP requests to specific components. Let's take URL/recipe/5 as an example. With the correct routing configuration, you can still use the web form recipedisplay. aspx to respond to this URL. In this case, the URL no longer represents the actual path. The word "recipe" indicates a parameter. The routing engine can use it to find the component used to process the recipe request. Number 5 represents the second parameter, which is used to display a specific recipe during processing. At this time, it is not recommended to embed database keywords into URLs by encoding. A better way is to use a URL like/recipe/tacos. This URL not only contains enough parameters to display a specific recipe, but also makes it easy for people to read and understand. It can reveal the intent of the end user, and include some important keywords for search engines.

A Brief History of URL rewriting in ASP. NET, when using a URL Ending with/recipe/tacos, someone traditionally needs to process the URL rewriting architecture. For more information about URL rewriting, see Scott Mitchell's authoritative article "performing URL rewriting in ASP. NET ". This article describes a common way to rewrite a URL using the HTTP module and the static rewritepath method of the httpcontext class in ASP. NET. Scott's article also details the advantages of friendly and modifiable URLs. Users who have used the rewritepath API in the past may be very aware of some strange phenomena and shortcomings in the rewrite method. The main problem facing rewritepath is how to change the virtual path used by this method during request processing. When using URL rewriting, you need to set the sender target of each web form (usually by rewriting the URL again during the request process) to avoid sending back to the Internally overwritten URL. In addition, most developers adopt one-way conversion mode when implementing URL rewriting, because URL rewriting logic cannot work in two directions through any simple mechanism. For example, it is very easy to give the URL rewriting logic a public-oriented URL and make it easy to return the internal URL of the web form. However, it is difficult to assign the rewrite logic to the internal URL of the web form and return the public URL required to enter the form. The latter is useful when you generate a hyperlink to other web forms hidden in the rewritten URL. The rest of this column describes how the URL routing engine solves these problems. Figure 1Routing, route processing program, and routing moduleThe routing and route processing program URL routing engine has three basic roles: routing, route processing program, and routing module. A route associates a URL with a route handler. The route class comes from the system. Web. Routing namespace. Its instances represent a route at runtime and describe the Routing Parameters and constraints. The route handler inherits from the system. Web. Routing. iroutehandler interface. This interface requires the route handler to implement the gethttphandler method, and this method returns an object that implements the ihttphandler interface. At the beginning, the ihttphandler interface was part of ASP. NET, while the web form (system. Web. UI. Page) was part of ihttphandler. When using web form routing, the routing handler needs to locate, instantiate, and return the correct web form. Finally, the routing module is embedded in the ASP. NET processing pipeline. This module intercepts incoming requests, checks URLs, and determines whether any defined matching route exists. This module will search for the relevant route handler that matches the route, and apply to the route handler for ihttphandler to process the request. The three main types I mentioned are as follows:Figure 1. In the next section, I will show how these three roles work.

To configure routes for ASP. NET websites or web applications, you must first Add a reference to the system. Web. Routing assembly .. The SP1 installer of Net Framework 3.5 installs this assembly into the Global Assembly Cache. You can find this Assembly in the standard "add reference" dialog box. You also need to configure the routing module in the ASP. NET pipeline. The routing module is a standard HTTP module. For IIS 6.0 and earlier versions and Visual Studio web development server, you can use

To run a website with the routing function in IIS 7.0, you must use two entries in Web. config. The first entry is the URL routing module configuration, which is located in <modules> of <system. webserver>. In addition, an entry in <system. webserver> Figure 2. For more information, see "IIS 7.0 configuration entries ". Figure 2 URL routing module configuration

<system.webServer>   <modules runAllManagedModulesForAllRequests="true">      <add name="UrlRoutingModule"             type="System.Web.Routing.UrlRoutingModule,                    System.Web.Routing, Version=3.5.0.0,                    Culture=neutral,                    PublicKeyToken=31BF3856AD364E35" />      <!-- ... -->    </modules>    

After the URL routing module is configured in the pipeline, it will bind itself to the postresolverequestcache and postmaprequesthandler events.Figure 3Displays a subset of MPs queue events. URL rewriting is usually performed during the beginrequest event. This event is the earliest triggered event in a request. When using URL routing, the routing handler performs routing matching and selection in the postresolverequestcache stage (this stage occurs after the authentication, authorization, cache query, and other processing stages. I will discuss the scheduled meaning of this event again in the content next to this column. Figure 3HTTP Request

The routing configuration is closely related to the routing processing program, but I first focus on the routing configuration code. The routetable class of the routing engine exposes the routecollection through its static routes attributes. You must configure all custom routes in this set before the application starts to execute the first request. This means that you need to use the global. asax file and application_start event.Figure 4The routing registration code required for "/recipe/brownies" to enter the recipedisplay. aspx web form is displayed. In the routecollection class, parameters of the add method include a friendly route name followed by the route itself. The first parameter of the route constructor is the URL mode. This mode consists of multiple URL segments that appear at the end of the URL pointing to the application (and after any segment required to enter the application's root ). For applications that are rooted in localhost/food,Figure 4The routing mode in will match localhost/food/recipe/brownies. Figure 4/recipe/brownies route registration code

protected void Application_Start(object sender, EventArgs e){    RegisterRoutes();}private static void RegisterRoutes(){    RouteTable.Routes.Add(        "Recipe",        new Route("recipe/{name}",                   new RecipeRouteHandler(                      "~/WebForms/RecipeDisplay.aspx")));}

IIS 7.0 configuration entries

If you want to use a non-extensible URL as shown in this example, you need to provide a true value for the runallmanagedmodulesforallrequests attribute. In addition, it may be strange to configure an HTTP handler for urlrouting. axd. This is a simple solution for enabling the routing engine to perform routing in IIS 7.0. In fact, the urlrouting module will rewrite the input URL ~ /Urlrouting. axd, which overwrites the URL back to the original input URL. It is very likely that the future version of IIS will be perfectly integrated with the routing engine, instead of using this solution. The content in braces indicates a parameter. The routing engine automatically extracts the value and puts it into the name/value dictionary. During the request duration, the dictionary will always exist. In the previous localhost/food/recipe/brownies example, the routing engine extracts the value "brownies" and uses "name" as the keyword to store it in the dictionary. When I introduce the routing handler code, you will learn how to use the dictionary. You can add any number of routes to the routetable as needed, but the routing order is very important. The routing engine uses these routes to test all input URLs based on the order in which the routes appear. The engine selects the first route that matches the pattern. To this end, you must first add the most special route. If a general route is added before the URL mode "{category}/{subcategory}", the routing engine will never find the route. In addition, note that the routing engine is case insensitive when performing mode matching. The overloaded version of the route constructor allows you to create default parameter values and apply constraints. When a parameter in a URL does not contain any value, defaults allows you to specify the default value of the routing engine to include it in the name/value parameter dictionary. For example, if the routing engine finds a scheme URL that does not contain the name value (such as localhost/food/recipe), "brownies" can be used as the default scheme name.

Related Article

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.