Tip/TRICK: URL rewriting with ASP. NET [Chinese version]

Source: Internet
Author: User
  • 14

[Original address] Tip/Trick:
Url Rewriting with ASP. NET
[Original article publication date] Monday, February 26,200 PM

Someone often asks me how to "Override" the URL dynamically to publish a relatively clean URL endpoint in their ASP. NETweb application. This blog post outlines several methods that you can use to cleanly map or rewrite URLs in ASP. NET and organize your URL structure as needed.

Why is URL ing and rewriting important?

The following are the most common scenarios for developers who want more flexibility on urls:

1)
To solve this problem, you must change the structure of the web page in your web application, but make sure that after you move the web page, old URLs added to favorites will not become dead links. Rewriting URLs allow you to transparently forward requests to a new Web address without error.

2) Google, Yahoo, and Live
In such a search engine, you can improve the search relevance of web pages on your website. Specifically, URL rewriting often makes it easier for you to embed keywords in the URLs of webpages on your website. Doing so will often increase the chance for others to click on your link. From using query string parameters to using full limits (fully
Qualified) URLs can also improve your priority in search engine results in some situations. Use the same case (same)
Case) and URL entry (for example, use weblogs.asp.net/scottgu instead
Weblogs.asp.net/scottgu/default.aspx) technology can also avoid reducing the web page ranking (pagerank) caused by crossing multiple URLs (avoid
Diluting your pagerank into SS multiple URLs) to increase your search results.

In a world where search engines are increasingly driving the access to websites, a slight increase in your web page rankings can bring a good return on investment (ROI) to your business ). Gradually, this drives developers to use URL rewriting and other SEO (Search Engine Optimization
) Technology to optimize the website (note, SEO is a fast-paced space, and suggestions for increasing your search relevance are evolving by month and month ). For some good suggestions on search engine optimization, I suggest you read SSW Rules to Better Google Rankings
(SSW's essentials for improving Google's ranking) And how URLs can affect top search engine ranking by MarketPosition
(How does a URL affect top-level search engine rankings.

Routine URL rewriting scenario

For the sake of this blog post, I will assume that we will build a set of e-commerce product catalog web pages in an application. Products are organized by type (such as books, videos, CD, DVD, etc ).

Let's assume that we have a webpage named Products. aspx at the beginning. by querying string parameters, we can accept a category name and filter the displayed Products accordingly. The URL of the category corresponding to this Products. aspx webpage looks like this:

Http://www.store.com/products.aspx? Category = books

Http://www.store.com/products.aspx? Category = DVDs

Http://www.store.com/products.aspx? Category = CDs

 

However, we do not want to use query strings to display each category. We want to modify the application so that each product category looks like a unique URL for the search engine, and embed keywords in the actual URL (instead of querying string parameters ). In the remaining sections of this blog post, we will discuss four different methods we can adopt to achieve this goal.

Method 1: Use the request. pathinfo parameter instead of the query string

I will demonstrate that the first method does not use URL rewriting at all, but uses the PathInfo attribute of the Request, a feature not well known in ASP. NET. To help explain the usefulness of this property, consider the following URLs in our e-store:

Http://www.store.com/products.aspx/Books

Http://www.store.com/products.aspx/DVDs

Http://www.store.com/products.aspx/CDs

One thing you will notice in the above URLs is that they no longer contain query string values. Instead, the value of the category parameter is appended to the URL, with Products. /parameter after aspx web page processor name
Value. Then, an automated search engine Crawler
Crawler) will interpret these URLs as three different URLs, instead of a URL with three different input values.
(The Search Engine ignores the file extension and treats it as another character in the URL ).

You may be wondering how to handle this additional parameter in ASP. NET. The good news is that this is very simple. You only need to use the PathInfo attribute of the Request.
The part after products. aspx. Therefore, for the above URLs, Request. PathInfo will return "/Books", "/DVDs", and
"/CDs" (in case you want to know, the Request Path attribute returns "/products. aspx ").

Then, you can easily write a function to obtain the product category, as shown in this case (the following function removes the previous slash character and returns only "Books", "DVDs ", or "CDs "):

Function getcategory () as string

If (Request. PathInfo. Length = 0) Then
Return ""
Else
Return Request. PathInfo. Substring (1)
End If

End Function

 

Sample download: A sample application that I created to demonstrate this technology can be downloaded here. This example is a good example of this technology. To deploy ASP. NET applications using this method, no server configuration changes are required. This technology also works well in the shared host environment.

Method 2: Use HttpModule to implement URL rewriting

The above Request. PathInfo technology is replaced by the HttpContext. RewritePath method provided by ASP. NET. This method allows developers to dynamically rewrite the processing path of the received URL, and then allow ASP. NET to continue executing the request using the previously rewritten path.

For example, you can show the following URLs to the public:

Http://www.store.com/products/Books.aspx

Http://www.store.com/products/DVDs.aspx

Http://www.store.com/products/CDs.aspx

 

In the outside world, the website has three separate webpages (this looks great for search crawlers ). Use
HttpContext's RewritePath method. When these requests enter the server, we can dynamically rewrite the received URL to a single Products. aspx webpage to accept the category name or PathInfo parameter of a query string. For example, we can use the Application_BeginRequest event in Global. asax to do this:

Void application_beginrequest (Object sender, eventargs e ){

String fullOrigionalpath = Request. Url. ToString ();

If (fullOrigionalpath. Contains ("/Products/Books. aspx ")){
Context. RewritePath ("/Products. aspx? Category = Books ");
}
Else if (fullOrigionalpath. Contains ("/Products/DVDs. aspx ")){
Context. RewritePath ("/Products. aspx? Category = DVDs ");
}
}

 

The disadvantage of coding such as the above is that it is boring and easy to make mistakes. I suggest you do not write it by yourself. Instead, you can use the online HttpModule to complete this task. Here are a few free httpmodules that you can download and use now:

  • Urlrewriter.net
  • Urlrewriting.net

These modules allow you to declare matching rules in the web. config file of your application. For example. use UrlRewriter In the config file.. Net module to map the above URLs to a single Products. on the aspx page, we only need to put this web. add the config file to our application (no encoding required ):

<? XML version = "1.0"?>

<Configuration>

<ConfigSections>
<Section name = "rewriter"
RequirePermission = "false"
Type = "Intelligencia. UrlRewriter. Configuration. RewriterConfigurationSectionHandler, Intelligencia. UrlRewriter"/>
</ConfigSections>

<System. web>

<HttpModules>
<Add name = "UrlRewriter" type = "Intelligencia. UrlRewriter. RewriterHttpModule, Intelligencia. UrlRewriter"/>
</HttpModules>

</System. web>

<Rewriter>
<Rewrite url = "~ /Products/books. aspx "to = "~ /Products. aspx? Category = books "/>
<Rewrite url = "~ /Products/CdS. aspx "to = "~ /Products. aspx? Category = CDS "/>
<Rewrite url = "~ /Products/DVDs. aspx "to = "~ /Products. aspx? Category = DVDs "/>
</Rewriter>

</Configuration>

 

The above httpmodule URL rewriting module also supports regular expressions and URL pattern matching (to avoid your
File ). Therefore, you do not need to write a category name. You can rewrite the matching rule as follows to dynamically extract the category name from the URL of any/products/[category]. aspx combination:

<Rewriter>
<Rewrite url = "~ /Products/(. +). aspx "to = "~ /Products. aspx? Category = $1 "/>
</Rewriter>

 

This makes your code extremely clean and scalable.

Sample download: A sample application that uses urlrewriter. Net to demonstrate this technology can be downloaded here.

This example is a good example of this technology. To deploy ASP. NET applications using this method, no server configuration changes are required. In medium
In the shared host environment, this technology is also effective (as long as you copy the file FTP/xcopy to the remote server, you do not need to install ).

Method 3: Use httpmodule in iis7 to rewrite a URL without an extension

The above httpmodule method contains. aspx in the URL you want to override
It can work with an extension or an extension that is set to ASP. NET. If you do this, you don't need any specific server configuration. You just need to copy your application to the remote server, and it will work normally.

But sometimes, the URL you want to rewrite either has a file extension that is not processed by ASP. NET (for example,. jpg,. gif, or
. Htm), or there is no extension at all. For example, we may want to display these URLs as public product directory webpages (note that they do not have the. aspx extension ):

Http://www.store.com/products/Books

Http://www.store.com/products/DVDs

Http://www.store.com/products/CDs

In IIS5 and IIS6, it is not easy to process the above URL using ASP. NET. In IIS 5/6
This makes it very difficult to rewrite these types of URLS in ISAPI extensions (ASP. NET is such an extension. What you need to do is to use the ISAPI filter in the IIS request pipeline (request
Pipeline) Earlier implementation rewriting. I will demonstrate how to implement this rewrite in IIS5/6 in the fourth method below.

But the good news is that IIS
7.0 makes it easy to handle such situations. You can execute an HttpModule anywhere in the IIS request pipeline, which means you can use the URLRewriter module above.
To process and override URLs without extensions (or even URLs with. asp,. php, or. jsp extensions ). The following shows how to configure IIS7:

<? XML version = "1.0" encoding = "UTF-8"?>

<Configuration>

<ConfigSections>
<Section name = "rewriter"
Requirepermission = "false"
Type = "intelligencia. urlrewriter. configuration. rewriterconfigurationsectionhandler, intelligencia. urlrewriter"/>
</Configsections>

<System. Web>

<Httpmodules>
<Add name = "urlrewriter" type = "intelligencia. urlrewriter. rewriterhttpmodule, intelligencia. urlrewriter"/>
</Httpmodules>

</System. Web>

<System. webserver>

<Modules runAllManagedModulesForAllRequests = "true">
<Add name = "UrlRewriter" type = "Intelligencia. UrlRewriter. RewriterHttpModule"/>
</Modules>

<Validation validateIntegratedModeConfiguration = "false"/>

</System. webServer>

<Rewriter>
<Rewrite url = "~ /Products/(. +) "to = "~ /Products. aspx? Category = $1 "/>
</Rewriter>

</Configuration>

 

Note the runallmanagedmodulesforallrequests attribute set to true in <system. webserver> <modules>. This attribute ensures that the urlrewriter. Net module from intelligencia (written before the official release of iis7) is called and has the opportunity to rewrite all URL requests (including folders) to the server ). The preceding web. config file is very cool:

1) It works on any iis7 machine. You do not need the Administrator to enable anything on the remote host. It can also be set to Medium
In the shared host environment.

2) Because I have configured urlrewriter IN THE In vs's built-in web server (Cassini), the same URL rewriting rule can also be used in iis7. Both support URL rewriting without an extension. This makes testing and development very easy.

IIS 7.0 will be used as a Windows Server later this year
The release of some Longhorn servers will support the go-live license with the release of beta3 in a few weeks. Thanks to all the new host features added to iis7, we expect that the host provider will be very quick to actively provide iis7 accounts, this means that you should soon be able to use the above URL rewriting support without extension. We will
Iis7 RTM
A URL rewriting module supported by Microsoft is released during the time period. This template is free of charge and can be used on iis7, this module also provides good support for advanced URL rewriting scenarios of all content on your Web server.

Sample download: A sample application that uses iis7 and urlrewriter. Net modules to demonstrate URL rewriting without extension can be downloaded here.

Method 4: Use isapirewrite in iis5 and IIS6 to rewrite URLs without extensions

If you do not want to use a URL without an extension to rewrite the IIS7, you 'd better use the ISAPI filter to rewrite the URL. I know there are two ISAPI filter solutions. You may want to take a look:

  • Helicon tech's ISAPI
    Rewrite: they provide a $99 (30-day free trial) isapi url rewrite product full version, as well as a free lightweight version.
  • Ionic's
    ISAPI rewrite: this can be downloaded for free (both source code and executable files can be downloaded)

I did not personally use the above products, although I have heard of these two products. Scott Hanselman and Jeff
Atwood has recently written a wonderful blog post about how to use these products and provides examples of how to configure matching rules in these products. Helicon Tech ISAPI
Rewrite Rules use the same syntax as Apache mod_rewrite, for example (from Jeff's blog post ):

[Isapi_rewrite]
# Fix missing slash on folders
# Note, this assumes we have no folders with periods!
RewriteCond Host :(.*)
RewriteRule ([^.?] + [^ .? /]) Http \: // $1 $2/[RP]

# Remove index pages from URLs
RewriteRule (. *)/default.htm $1/[I, RP]
RewriteRule (. *)/default. aspx $1/[I, RP]
RewriteRule (. *)/index.htm $1/[I, RP]
RewriteRule (. *)/index.html $1/[I, RP]

# Force proper www. prefix on all requests
RewriteCond % HTTP_HOST ^ test \. com [I]
RewriteRule ^/(. *) http://www.test.com/#1 [RP]

# Only allow whitelisted referers to hotlink images
RewriteCond Referer :(?! Http ://(? : Www \. good \. com | www \. better \. com). +
RewriteRule .*\.(? : Gif | jpg | jpeg | png)/images/block.jpg [I, O]

 

Be sure to read Scott and Jeff's posts to learn more about these ISAPI modules and what you can do with them.

Note: one disadvantage of using the ISAPI filter is that the shared host environment generally does not allow you to install such components. Therefore, if you want to use them, you need a dedicated virtual host server, A dedicated host server is required. However, if you have a host plan that allows you to install ISAPI, this will provide maximum flexibility in IIS5/6, so that you can transition to IIS7.

Process ASP. NET PostBack in URL rewriting

When using ASP. NET and rewriting URLs, we often encounter a difficult issue related to processing postback scenarios. Specifically, when you place a <form
Runat = "server"> control, ASP. NET
The action attribute of the output identifier automatically points to the current page by default. This problem occurs when URL rewriting is used. <form>
The URL displayed by the control is not the original requested URL (for example,/products/books), but the rewritten URL (for example,/products. aspx? Category = books ). This means that when you make a postback to the server, the URL is no longer the one you used to clean up.

In ASP. NET 1.0 and 1.1, we often resort to inheritance <form>
Controls generate their own controls to correctly output the Action attributes to be used. Although this works, the results are messy, because it means that you need to update all your pages to use this other form control, and sometimes in the visual
Studio WYSIWYG designer also has problems.

The good news is that in ASP. NET 2.0, there is a cleaner trick you can use to override the action attribute of the <form> control. Specifically, you can use the new ASP. NET
2.0 The control adapter extended architecture is used to customize the control output and overwrite the value of the action attribute with the value you provide.This does not require any encoding changes on your. ASPX page.Add a. Browser file in your/app_browsers folder and register and use a control adaptation class to output new Action attributes.

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.