Using route__.net in asp.net webform

Source: Internet
Author: User
Tags html tags httpcontext visual studio 2010

Students who have used asp.net mvc may have some contact with route, and may use URL Rewrite to implement similar functions in ASP.net webform. This article describes the use of route in ASP.net WebForm.

1. Locate the Global.asax file and create a new one without this file.

2. Add RegisterRoutes method

Code highlighting produced by Actipro Codehighlighter (freeware) http://www. codehighlighter.com/--> 1 public static void RegisterRoutes (RouteCollection routes)
{
    //default page
    routes. Mappageroute (
        "Defautl",
        "" ","
        ~/folder1/webform1.aspx "
        );

    Routes a URL in the form of {Folder}/{webform}
    routes. Mappageroute (
        "WebForm1",
        "{folder}/{webform}",
        "~/{folder}/{webform}.aspx"
        );

    Route (with parameters) routes the URL in the form of {folder}/{page}
    . Mappageroute (
        "WebForm2",
        "{floder}/{webform}/{parameter}",
        "~/{floder}/{webform}.aspx"
    );

}

3. Use the Registerroute method in the Application_Start method.

protected void Application_Start (object sender, EventArgs e)
{
     registerroutes (routetable.routes);
 }

If you want to get the parameters in the URL, you can refer to the following code

string parameter = page.routedata.values["parameter"] as String;

It gets the argument that the placeholder is parameter. The value of the parameter parameter, such as ~/FOLDER2/WEBFORM3/ABC, is ABC, but if the ~/FOLDER2/WEBFORM3?PARAMETER=ABC is encountered, it does not seem to get parameter parameter values. can use

string parameter = request.params["parameter"] as String;

To get. Demo Practice for asp.net 4: URL routing improvement support

Starting with the. NET Framework 3.5 SP1, Microsoft introduced ASP.net routing support to achieve a complete decoupling of the URL of a particular resource from the physical file on its corresponding Web server. With ASP.net routing support, developers can define a set of routing rules that map the routing pattern to a class that generates the appropriate content. For example, you can map the url "Categories/categoryname" to a class that receives CategoryName and eventually generates a set of HTML tags that correspond to this kind of product information displayed in a grid. With such a mapping, users can access www.yoursite.com/Categories/Beverages to view all product information for the beverage category.

In. NET 3.5 SP1, ASP. NET routing is primarily designed for asp.net MVC applications, although ASP.net routing support can also be implemented in Web Forms applications that are supported by the ASP.net MVC framework. However, implementing ASP.net routing in a Web Forms application involves a lot of extra work.

In Web Forms, we typically map the routing pattern to an actual asp.net page. To do this, we need to create a routing class to call when routing URLs are requested, and in some sense to dispatch the request to the appropriate ASP.net page. For example, to map a route to a physical file, such as mapping Categories/categoryname to showproductsbycategory.aspx, we need the following three steps:

(1) Define the mapping in the Global.asax file to map the routing pattern to a routing class;

(2) Creating a routing class that resolves URLs, stores all routing parameters to locations where the target page can be accessed (such as Httpcontext.items), and returns an instance of the target page or HTTP processor that handles the request route;

(3) Write code in the target page to get the routing parameters and use them to generate the page content.

And without saying how much it costs to read just the preceding statement (not to mention writing it), you can fully imagine that performing ASP.net routing in a Web Forms application is not necessarily the most straightforward task for developers.

Thankfully, ASP.net 4.0 greatly simplifies the use of ASP.net routing in Web Forms applications by adding a set of classes and assistant methods. With ASP.net 4.0, you will be able to define routing rules more easily, rather than creating a custom routing handler class. This article will discuss the improvement support in detail. First, ASP. NET Routing Technology Overview

Asp. NET route can be used to create clean, concise and search engine friendly URLs by cleanly decoupling the URL from the file name of the Web page. For a detailed discussion of why you should use ASP.net routing in your Web application, please refer to other relevant articles.

Broadly speaking, ASP. NET routing allows developers to define routing rules that map a routing pattern (such as Categories/categoryname) to a class that processes requests. These routing rules are defined in the Application_Start event handlers in file global.asax when the application is started.

In Web Forms applications, we may already have asp.net pages that generate the content we're interested in, and we just need to map the routing patterns to these asp.net pages through routing rules-by putting any routing parameters (such as CategoryName) Mapped to the ASP.net page for implementation. When ASP.net routing is used in asp.net 3.5 SP1, there is no way to directly map the routing pattern to the ASP.net page. Instead, we must create a routing class that is responsible for passing information about incoming requests and must return an HTTP handler to process the request. Typically, a routing class in a Web Forms application performs the following steps:

(1) To resolve Web sites as needed, perhaps to study some routing parameters and to make decisions based on these values.

(2) load any route parameters from the URL that needs to be passed to the ASP.net page or HTTP handler (which will process the request). In conclusion, we want to make sure that the ASP.net page generates the actual content because this request knows the value of all routing parameters, such as CategoryName. One way to convey such information is to put them in the Httpcontext.items collection-a collection that serves as a repository of data for a particular length of request information.

(3) Returns an instance of the ASP.net page or HTTP handler that performs the above processing.

Typically, these routing handler classes have similar characteristics. You store the routing parameters in the Httpcontext.items collection and then create and return an instance of the ASP.net page that is responsible for generating the corresponding content of the URL. Although routing classes have similar characteristics, writing these classes is a lengthy task because each new route requires a new handler class that needs to implement almost the same tasks as the previous class.

Another challenge in using asp.net routing in ASP.net 3.5 SP1 is primarily related to the ASP.net page that is responsible for generating the final content. This page must be read from the Httpcontext.items collection (or other routing handler classes that store them) by argument. In addition, the syntax for generating routing-friendly URLs (such as categories/categoryname) for a hyperlink or Response.Redirect call is also a bit verbose and confusing.

In ASP.net 4.0, routing support has been enhanced, including some new routing-related methods, making it simpler to define routing rules that map to actual asp.net pages. In ASP.net 4.0, you no longer need to create a custom routing handler class as an intermediary, but simply refer to the ASP.net page directly from the routing rules in the Global.asax file. When a asp.net page is specified from a routing rule, the route parameters are automatically stored in a new Routedata collection, which can be accessed from the ASP.net page through the page.routedata structure. More importantly, include a custom parameter control in. NET Framework 4.0, so that you can use the values in the Routedata from the ASP.net data source controls (such as SqlDataSource and LinqDataSource, etc.) in a declarative manner. It also provides methods to generate routing-friendly URLs and redirect to a routing-friendly URL.

This article will focus on ASP.net support for routing system improvement in ASP.net 4.0. The demo program provided in this article is a Web Forms application, which is the front end of a Northwind Traders Web site. It uses ASP.net routing support to create simple and search engine friendly URLs. For example,/categories/all will display all categories,/categories/beverages will list all products that belong to the beverage category, and/products/chai will display details about the product chai.

Note that in order to use ASP.net routing support in the ASP.net 3.5 SP1, you need to explicitly add a reference to the System.Web.Routing assembly in your project and add some markup to the Web.config profile. These steps are no longer needed when using ASP.net 4.0, and the syntax used to define routing rules in the Global.asax file is shorter, simpler, and more readable.

A detailed description of the steps used in asp.net routing in ASP.net 4.0 is given later in this article. ii. use of asp.net 4.0 routing

The following is a detailed description of the use of ASP.net routing in asp.net 4.0.

0. Premises

The demo program provided in this article uses the ASP.net routing feature that is newly added to ASP.net 4.0. If you use Visual Studio 2010 or the Visual Web Developer 2010 (or later), you have the right premise.

1. Define routing rules in file global.asax

To use the ASP.net routing system, you need to define one or more routes when the application starts. The method is to add a global application class file (Global.asax) to your project. In this file, we will register these routes in the Application_Start event.

The route defined in the Global.asax file indicates what routing handler is responsible for what URL pattern is handled. In an MVC application, a popular pattern is controller/action/id; this means targeting/products/view/aniseed syrup or categories/edit/ Beverages requests are processed by the configured routing handler. You can have enough flexibility to define what routing is in your application. For example, you can define multiple parts of a pattern, define a missing part of the default value, and even define a restriction section for some input types.

This article demonstrates that the program is a simple data-driven application that uses the Northwind database and accepts URLs for the following patterns:

/categories/all-Lists all product types in the database;

/categories/categoryname-lists product information corresponding to a specific type;

/products/productname-displays information about a specific product.

Therefore, I defined three routes in the Application_Start event handler for the Global.asax file, as shown in the following code. (Note: The RouteTable object and RouteCollection class are located in the System.Web.Routing namespace.) )

In the Application_Start method, we call the RegisterRoutes and pass in the parameter routetable.routes of the routecollection type. Next, in the RegisterRoutes method, call the Mappageroute method of the RouteCollection class, which defines a routing pattern to the ASP.net page's route map. For example, the first time we called the Mappageroute method, we created a routing pattern named "All Categories"-it was responsible for mapping the routing pattern categories/all to asp.net page ~/allcategories.aspx.

The next two Mappageroute method calls use parameters to create a routing pattern. Where the "View Product" route maps the schema Products/{productname} to the ASP.net page ~/viewproduct.aspx. Here, {ProductName} is a parameter, meaning that any products/productname form request will be routed to the ~/viewproduct.aspx page. Soon you will see that the value of the {ProductName} parameter can be accessed from the page ~/viewproduct.aspx through the Page.routedata parameter.

2. Create a asp.net page to process the request

With ASP.net 4.0, you no longer need to create a custom routing handler class. When you use the Mappageroute method, all of this will be done automatically by the underlying library for you. The only thing left is to create the ASP.net page (allcategories.aspx,categoryproducts.aspx and viewproduct.aspx) that handles the request. Of course, the three pages in this article are fairly straightforward-they all use data source controls and are programmatically bound to the database results of categories or products tables obtained by routing parameters.

void Application_Start (object sender, EventArgs e)

{

registerroutes (routetable.routes);

}

void RegisterRoutes (routecollection routes)

{

//Register a route for Categories/all

routes.  Mappageroute (

"All Categories",//Routing name

"Categories/all",///Routing URL

"~/allcategories.aspx"//Processing routing pages

);

To handle routing

//More information for Categories/{categoryname}, refer to http://forums.asp.net/p/1417546/3131024.aspx

routes. Mappageroute (

"View Category",//Routing name

"Categories/{*categoryname}",//Routing URL

) ~/  Categoryproducts.aspx "//Processing of routed web pages

);

Register a route for products/{productname}

routes. Mappageroute (

"View Product",//Routing name

"Products/{productname}",//Routing URL

"~/viewproduct.aspx"//  Processing the routed web page

);

}

This demo program uses the Linq-to-sql tool to implement data access. You will find a northwind.dbml file under the App_Code folder, which creates a NorthwindDataContext class. The Viewproduct.aspx page contains a DetailsView control in which fields are used to display the name of the product, the vendor, the number of units, the price, and other relevant information. The code-behind class for the page has the following (partially omitted) code:

protected void Page_Load (object sender, EventArgs e)

{

Dvproductinfo.datasource = new product[] {Product};
   Dvproductinfo.databind ();

private Product _product = null;

Protected product Product

{

get

{

if (_product = = null)

{

string productName = Page.  routedata.values["ProductName"] as String;

NorthwindDataContext DataContext = new NorthwindDataContext ();

_product = DataContext.Products.Where (p => p.productname = = ProductName).  Singleordefault ();

return

_product;

}

}

In the Page_Load event handler above, the DetailsView control is bound to the product object returned by the Product property. Here, the Product property reads the ProductName parameter value from the URL in the Page.routedata collection, using the syntax: page.routedata.values["ProductName". Then, use the ProductName parameter values in the LINQ query to retrieve information about the specific product.

The screenshot below shows the Viewproduct.aspx page in the run. The Web page corresponds to the/products/chai, and details about the Chai are displayed on this page.

The process of setting up ASP.net routing in asp.net 4.0 is this! However, implementing the above procedure in the ASP.net 3.5 SP1 requires five steps, rather than two steps. third, generate routing-friendly URLs

When you create a hyperlink or navigate from one page to another through the Response.Redirect method, it is ideal to use the routing pattern defined in global.asax (instead of referencing the ASP.net page pattern using its actual name). For example, there is a viewproducts.aspx page with a link-this link allows you to return to all product information that displays the selected product category, and this product category is linked to Categories/categoryname, Where CategoryName is the product category name, information is displayed for this category of products. At this point, you can use the Page.getrouteurl method to generate these routing-friendly URLs. This method has many overloaded versions, but the simplest version receives only two parameters: the route name and the value of the parameter.

For example, to get the correct URL to return to the Categories/categoryname page, you can use the following syntax:
Page.getrouteurl ("View Category", new {CategoryName = CategoryName});

In this case, "View Category" is the name of the Global.asax middle rule defined in the file, and CategoryName is the value of the CategoryName parameter that appears in the URL. Another more specific example is:
Page.getrouteurl ("View Category", new {CategoryName = "beverages"});

In addition, there is another new version of the Response.Redirect method, named Response.redirecttoroute. Like the Page.getrouteurl method, this method can receive routing names and parameter values, and then redirect users to the appropriate, routing-friendly URLs. The following example shows how to redirect a user to a view of a particular product:
Response.redirecttoroute ("View Product", new {ProductName = ProductName}); Iv. Conclusion

Asp. NET routing is a powerful library provided by the. NET Framework, which enables a complete decoupling of URLs from underlying physical files. Since the introduction of ASP.net 3.5 SP1, ASP. NET routing is initially applied to the development of ASP.net MVC applications. Although it can also be used in Web Forms applications, it takes tedious steps to configure it and appears to cause unnecessary and repetitive code.

asp.net 4.0 strengthens the ASP.net routing library and provides more flexible and intuitive usage scenario support for Web Forms applications. As you can see in this article, mapping a routing pattern to a ASP.net page requires only a few lines of code to be added to the Global.asax, instead of creating a custom routing handler class. At the bottom, ASP. NET routing library automatically saves routing parameters to the Routedata collection-you can then access it from the page class. Also, these routedata values can be accessed declaratively through data source controls such as SqlDataSource and ObjectDataSource.

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.