Type:. NET; problem: ASP. NET-routed; Result: ASP-4

Source: Internet
Author: User

ASP. NET Routing . NET Framework 4

Updated: November 2007

ASP. NET routing allows you to use URLs that do not have to be mapped to specific files in your Web site. Because URLs do not have to be mapped to files, URLs can be used in WEB applications that are descriptive user actions and therefore easier for users to understand.

In an ASP. NET application that does not use routing, incoming requests to URLs are typically mapped to physical files on disk, such as. aspx files. For example, a request to http://server/application/Products.aspx?id=4 maps to a file named Products.aspx that contains code and markup to render a response to the browser. A Web page uses the id=4 query string value to determine what type of content to display, but that value may not be meaningful to the user.

In ASP. NET routing, you can define a URL pattern that contains placeholders for the values that are used when processing URL requests. At run time, the URL portion that follows the application name is parsed as discrete values based on the URL pattern that you define. For example, when Http://server/application/Products/show/beverages is requested, the route Analyzer can value products , show,and Beverages The handler that is passed to the request. Instead, in a request that is not managed by a URL route, the/products/show/beverages fragment is interpreted as the path to a file in the application.

You can also use the URL pattern to programmatically create a URL that corresponds to a route. This enables you to centralize the logic used to create hyperlinks in your ASP.

ASP. NET Routing and URL rewriting

ASP. NET routing differs from other URL rewriting scenarios. URL rewriting processes incoming requests by actually changing the URL before sending the request to the Web page. For example, an application that uses URL rewriting may change the URL from /products/widgets/to /products.aspx?id=4. In addition, URL rewriting typically does not have the appropriate API to create a schema-based URL. In URL rewriting, if you change the URL pattern, you must manually update all the hyperlinks that contain the original URL.

Because ASP. NET routes can fetch values from URLs, the URLs are not changed when processing incoming requests. If you must create a URL, pass the parameter value to the method that generates the URL for you. To change the URL pattern, change the pattern in a location, and all links that you create in the application that are based on that pattern will automatically use the new schema.

Defining URL Routes

The URL pattern defined is called "Routing". In routing, you can specify a placeholder that maps to a value parsed from a URL request. You can also specify constant values that are used to match URL requests.

In routing, you can define placeholders (called "URL parameters") by enclosing placeholders in curly braces ({and}). The /character is interpreted as a delimiter when parsing the URL. The information in the route definition that is not a delimiter and is not enclosed in curly braces is treated as a constant value. Assigns a value that is extracted from between two delimiters to a placeholder.

You can define multiple placeholders between delimiters, but you must separate them with a constant value. For example,{language}-{country}/{action} is a valid routing pattern. However, because there is no constant or delimiter between the placeholders, {language}{country}/{action} is not a valid pattern. Therefore, the route cannot determine where to separate the value of the language placeholder from the value of the country placeholder.

The following shows an example of a valid routing pattern and some URL requests that match the pattern.

Route definition

Example of a matching URL

{Controller}/{action}/{id}

/products/show/beverages

{table}/details.aspx

/products/details.aspx

Blog/{action}/{entry}

/blog/show/123

{Reporttype}/{year}/{month}/{day}

/sales/2008/1/5

{Locale}/{action}

/zh-cn/show

{Language}-{country}/{action}

/zh-cn/show

Typically, you add a route in a method that is called by the handler for the Application_Start event in the Global.asax file . This method ensures that the routes are available when the application starts. It also enables you to call methods directly when you are unit-testing your application. If you want to call a method that registers a route directly when you are unit-testing the application, the method must be static (Shared in Visual Basic ) and must have a routecollection parameter.

You can add routes by adding routes to the static Routes property of the RouteTable class. The Routes property is a RouteCollection object that stores all the routes for an ASP. The following example shows the code that adds a Route object from the Global.asax file that defines the two URL parameters named action and CategoryName.

C#vb
protected void Application_Start (object sender, EventArgs e) {    registerroutes (routetable.routes);} public static void RegisterRoutes (RouteCollection routes) {    routes. ADD (New Route    (         "Category/{action}/{categoryname}"         , New Categoryroutehandler ())    );
set default values for route parameters

You can assign a default value to a parameter when you define a route. If the URL does not include a value for the parameter, the default value is used. By assigning a dictionary to the defaults property of the route class, you can set the default value for the route. The following example shows a route that contains a default value.

C#vb
void Application_Start (object sender, EventArgs e) {    registerroutes (routetable.routes);} public static void RegisterRoutes (RouteCollection routes) {  routes. ADD (New Route  (     "Category/{action}/{categoryname}"          new Categoryroutehandler ()  )    {       Defaults = new RouteValueDictionary            {{"CategoryName", "food"}, {"Action", "Show"}}  );

The route definition shown in the example (using the default value for food for CategoryName and the default for show for action) gets the results listed in the following table when the ASP. NET route handles URL requests.

Url

Parameter values

/category

Action = "Show" (default value)

CategoryName = "Food" (default value)

/category/add

Action = "Add"

CategoryName = "Food" (default value)

/category/add/beverages

Action = "Add"

Categoryname= "Beverages"

handle a variable number of segments

Sometimes you need to process URL requests that contain a variable number of URL segments. When defining a route,you can specify that the last parameter should match the rest of the URL by marking the asterisk (*) parameter. Thus the parameter is called the "catch all" parameter. Routes with all capture parameters will also match the URLs of any values that do not contain the last parameter. The following example shows a route pattern that matches an unknown number of segments.

Query/{queryname}/{*queryvalues}

When an ASP. NET route handles a URL request, the route definition shown in the example gets the results listed in the following table.

Url

Parameter values

/query/select/bikes/onsale

QueryName = "Select"

Queryvalues = "Bikes/onsale"

/query/select/bikes

QueryName = "Select"

Queryvalues = "Bikes"

/query/select

QueryName = "Select"

Queryvalues = Empty string

to add a constraint to a route

In addition to matching URL requests to the route definition by the number of parameters in the URL, you can also specify that the values in the parameters satisfy a specific constraint. If a URL contains a value other than the constraint of the route, the route is not used to process the request. Add a constraint to ensure that the URL parameter contains values that will work in the application.

Constraints are defined by using regular expressions or by using an object that implements the Irouteconstraint interface. When you add a route definition to the Routes collection, you also add a constraint by creating a RouteValueDictionary object that contains validation tests. This object is then assigned to the Constraints property. The keywords in the dictionary identify the parameters that the constraint applies to. The value in the dictionary can be a string representing a regular expression, or it can be an object that implements the Irouteconstraint interface.

When a string is supplied, the route will treat the string as a regular expression and check whether the parameter value is valid by calling the IsMatch method of the Regex class. Regular expressions are always treated as case-insensitive. For more information, see. NET Framework Regular Expressions.

When the Irouteconstraint object is supplied, the ASP. NET route checks whether the parameter value is valid by calling the Irouteconstraint object's Match method. The Match method returns a Boolean value that indicates whether the parameter value is valid.

The following example shows a constraint that restricts the values contained in the locale and year parameters.

C#vb
void Application_Start (object sender, EventArgs e) {    registerroutes (routetable.routes);} public static void RegisterRoutes (RouteCollection routes) {    routes. ADD (New Route    (      "{locale}/{year}"         , new Reportroutehandler ()    )       {          Constraints = new RouteValueDictionary           {"locale", "[A-z]{2}-[a-z]{2}"},{year, @ "\d{4}"}}       );

When routing a URL request, the route definition shown in the previous example generates the results listed in the following table.

Url

Results

/zh-cn

No match. both locale and year are required.

/zh-cn/08

No match. A constraint of year requires 4 digits.

/zh-cn/2008

Locale = "ZH-CN"

Year = "2008"

scenario with no routing applied

By default, routing does not process requests that map to existing physical files on the WEB server. For example, if a physical file exists on the products/beverages/coffee.aspx, the route does not handle the http://server/application/Products/Beverages/Coffee.aspx The request. Even if a defined pattern is matched, such as {Controller}/{action}/{id}, the route does not process the request.

If you want the route to handle all requests, including requests to files, you can override the default behavior by setting the Routeexistingfiles property of the RouteCollection object to true. When this value is set to true, all requests that match the defined pattern are handled by the route.

You can also specify that routes should not process certain URL requests. By defining a route and specifying that the Stoproutinghandler class should be used to handle the pattern, the route is prevented from processing some specific requests. When a Stoproutinghandler object processes a request, the Stoproutinghandler object prevents the request from being processed as a route in any other way. Instead, the request is processed as an ASP. NET page, Web service, or other ASP. For example, you can add the following route definition to prevent routing requests that process WebResource.axd files.

C#vb
public static void RegisterRoutes (RouteCollection routes) {  routes. ADD (New Route ("{resource}.axd/{*pathinfo}", New Stoproutehandler ()));
how URLs match the route

The route also attempts to match the URL of the request to the route when it processes the URL request. Matching a URL request to a route depends on all of the following conditions:

    • Includes the defined route pattern or default route pattern, if any, in the project type.

    • The order in which routes are added to the Routes collection.

    • All default values that have been provided to the route.

    • Any constraints that have been provided to the route.

    • Whether to define a route to handle requests that match physical files.

To avoid the wrong handlers processing requests, you must consider all of the above conditions when defining the route. The order of the Route objects that appear in the Routes collection is important. The route will try to match throughout the routing of the collection. When a match occurs, more routes cannot be calculated. In general, routes are added to the Routes property in order of decreasing the specificity of the route definition.

For example, suppose you add a route using the following pattern:

    • Route 1:{controller}/{action}/{id}

    • Route 2:products/show/{id}

Route 2 will never process the request because Route 1 is calculated first and the match will be matched to the request for Route 2. requests to http://server/application/products/show/bikes appear to match Route 2, but are handled by Route 1 using the following values:

    • Controller = Products

    • Action = Show

    • id = Bikes

If the request is missing a parameter, the default value is used. Therefore, the route may cause unexpected requests to match. For example, suppose you add a route using the following pattern:

    • Route 1:{report}/{year}/{month}, using default values for year and month.

    • Route 2:{report}/{year}, using the default value for year.

Route 2 will never process the request. Route 1 may be used for monthly reports, while Route 2 may be used for annual reports. However, the default value in Route 1 means that all requests that apply to Route 2 will be matched.

You can avoid ambiguity by including constants in the schema, such as annual/{report}/{year} and Monthly/{report}/{year}/{month}.

If the URL does not match any of the Route objects defined in the RouteTable collection, the ASP. NET route will not process the request. Instead, the processing is passed to an ASP. NET page, Web service, or other ASP.

To create a URL from a route

You can use routing to generate URLs when you want to centralize the logic used to construct URLs. Create a URL by passing the parameter value as a dictionary to the GetVirtualPath method of the RouteCollection object. The GetVirtualPath method finds the first route in the RouteCollection object that matches a parameter in the dictionary. The matching route is used to generate the URL. The following example shows the route definition.

C#vb
public static void RegisterRoutes (RouteCollection routes) {  routes. ADD (New Route  (     "Category/{action}/{categoryname}"          new Categoryroutehandler ()  )    {       Defaults = new RouteValueDictionary {{"CategoryName", "Food"},            {"Action", "Show"}}  );

The following example shows a control that creates a URL based on a route.

Vb
Dim urlparameters as Routevaluedictionaryurlparameters = new RouteValueDictionary (new with {. CategoryName = "Beverages", _        . Action = "Summarize"}) Hyperlink1.navigateurl = RouteTable.Routes.GetVirtualPath _    (context, Urlparameters). VirtualPath

C#
Hyperlink1.navigateurl = RouteTable.Routes.GetVirtualPath  (context,  new RouteValueDictionary {     " CategoryName "," Beverages "},     {" Action "," Summarize "}}  ). virtualpath;

When you run this code, theHYPERLINK1 control will contain the value "Category/summarize/beverages" in the NavigateUrl property.

When you create a URL from a route, you can specify which route to use to create the URL by including the name of the route. For more information, see How to: Construct URLs by routing ...

Please seeConcept Understanding ASP. NET Infrastructure Community Additional resourcesAdd

Type:. NET; problem: ASP. NET-routed; Result: ASP-4

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.