Code for rewriting URLs in asp.net-practical tips

Source: Internet
Author: User
Tags httpcontext hosting shared hosting visual studio
I'm often asked to guide how to dynamically "rewrite" URLs to publish relatively clean URL endpoints in their asp.netweb applications. This blog post outlines several methods that you can use to map or rewrite URLs cleanly in asp.net, and to organize the structure of your URLs according to your own needs.

Why is URL mapping and rewriting important?
The following are the most common scenarios that developers want to have greater flexibility for URLs:

1 deal with situations where you want to change the structure of your Web pages, but you also make sure that the old URLs that are collected will not become dead links when you move the pages. The rewrite URL allows you to transparently transfer the request to a new web address without error.

2 improve the search relevance of your Web pages in search engines like Google,yahoo and Live. Specifically, URL rewriting often makes it easier to embed keywords into the URLs of your Web pages, which often increases the chances of someone clicking on your link. The use of query string parameters to URLs that use fully qualified (fully qualified) can also improve your prioritization in search engine results in some situations. Use the same capitalization (same case) and URL entry using the force referring link (for example, using Weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) Technology also avoids the reduction of page rank (pagerank) caused by multiple URLs (avoid diluting your PageRank across URLs) to increase your search results.

In a world where search engines are increasingly driving web sites, a slight increase in your page rankings can give your business a good return on investment (ROI). Gradually, this drives developers to use URL rewriting and other SEO techniques to optimize the site (note, SEO is a fast paced space to increase your search relevance to the proposal month of evolution). To get some good advice on SEO, I suggest you read the SSW rules to Better Google rankings (SSW's way to improve Google rankings) and marketposition about how URLs can affect top search engine ranking (how the URL will affect the ranking of top-level SEO) articles.

URL rewrite scenario for routines
For the sake of this blog post, I will assume that we will build an E-commerce product catalog page in an application that is organized by type (e.g., books, videos, Cd,dvd, etc.).

Let's assume that at first we have a page called Products.aspx, which accepts a category name through a query string parameter, and filters the displayed product accordingly. The URL of the corresponding category to this products.aspx page 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

But we don't want to use the query string to present each category, and we want to modify the application so that each product category looks like a unique URL to the search engine and embeds the keyword in the actual URL (not through the query string argument). In the remainder of this blog post, we will discuss 4 different approaches we can take to achieve this.

Method One: 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 rather uses a feature that is not well known in asp.net, the pathinfo attribute of the request. To help explain the usefulness of this attribute, consider the following URLs in our electronics 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'll notice in these URLs is that they no longer contain the query string value, and instead, the value of the class parameter is appended to the URL, in the form of the/parameter value after the Products.aspx page processor name. Then an automated search engine crawler (search engine crawler) interprets these URLs as three different URLs, rather than a URL with three different input values (the search engine ignores the file name extension and treats it as just another character in the URL).

You might want to know how to handle this additional parameter in asp.net. The good news is that it's very simple. Just use the PathInfo property of the request, which returns the part of the URL that follows the products.aspx. So, for the above URLs, Request.pathinfo will return "/books", "/dvds", and "/cds" (if you want to know, Request's Path property returns "/products.aspx").

You can then easily write a function to get the product category, like this (the following function removes the preceding 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 Downloads: A sample application that I have built to show this technology can be downloaded here. The good thing about this sample and this technique is that asp.net applications that use this method for deployment do not require any server configuration changes. In a shared hosting environment, this technology is also effective.

Method Two: Implement URL rewriting using HttpModule
The substitution method for the above Request.pathinfo technique is to use the Httpcontext.rewritepath method provided by ASP.net. This method allows the developer to dynamically rewrite the processing path of the received URL, and then let asp.net use the path just rewritten to continue executing the request.

For example, we can choose to present the following URL to the public:


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

On the outside, there are three separate Web pages (this looks great for search crawlers). By using the HttpContext RewritePath method, we can dynamically rewrite the received URL into a single Products.aspx Web page to accept the category name or PathInfo parameter of a query string when these requests have just entered the server. 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 writing code like the one above is that it's tedious and easy to make mistakes. I suggest you not write it yourself, but use the HttpModule on the Internet to do the work. Here are a few free httpmodule you can download and use now:

Urlrewriter.net
Urlrewriting.net
These modules allow you to express the matching rules in a declarative manner in the Web.config file you are applying. For example, using the Urlrewriter.net module in your application's Web.config file to map the above URLs to a single products.aspx page, we can simply add the Web.config file to our application ( Without any coding):


<?xml version= "1.0"?>

<configuration>

<configSections>
<section name= "Rewriter"
Requirepermission= "false"
Type= "Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.urlrewriter"/ >
</configSections>

<system.web>

<add name= "Urlrewriter" type= "Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.urlrewriter"/>

</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 HttpModule URL rewrite module above also supports regular expressions and URL pattern matching (to avoid the hard writing of each URL in the Web.config file). So, instead of writing a dead category name, you can rewrite the matching rule as follows, dynamically taking the class name from any/products/[class].aspx combination URL:


<rewriter>
<rewrite url= "~/products/(. +). aspx" to= "~/products.aspx?category=$1"/>
</rewriter>


This makes your coding extremely clean and very scalable.

Sample Download: A sample application that I built to show this technology using the Urlrewriter.net module can be downloaded here.

The good thing about this sample and this technique is that asp.net applications that use this method for deployment do not require any server configuration changes. In the context of a shared host set to the Medium Trust security level (medium), this technology is also effective (as long as the file is ftp/xcopy to the remote server, no installation is required).

Method Three: Use HttpModule in IIS7 to implement URL overrides with no extension
The above HttpModule method works if the URL you want to rewrite contains an. aspx extension or another extension that is set to asp.net processing. If you do this, you don't need any specific server configuration, you just copy your application to a remote server and it will work correctly.

But sometimes, the URL you want to rewrite either has a file name extension (such as. jpg,. gif, or. htm) that is not handled by ASP.net, or there is no extension at all. For example, we might want to present these URLs as open Product catalog pages (Note that they do not have an. 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 use asp.net to process URLs like the above. IIS 5/6 enables the ISAPI extension (ASP. NET is such an extension, it is very difficult to rewrite these types of URLs. What you need to do is rewrite the earlier implementation of the IIS request pipeline using the ISAPI filter (pipeline). I'll demonstrate how to implement such an override in Iis5/6 in the fourth method below.

But the good news is that IIS 7.0 makes it easy to handle situations like this. You can now execute a httpmodule anywhere in the IIS request pipeline, which means you can use the Urlrewriter module above to process and override URLs without extensions (even URLs with. asp,.php, or. jsp extensions). Here is a demonstration of how you can configure the 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>

<add name= "Urlrewriter" type= "Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.urlrewriter"/>

</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 property that is set to true in the <system.webServer> <modules> section. This property ensures that the Urlrewriter.net module from Intelligencia (written prior to the formal release of IIS7) is invoked and has the opportunity to rewrite all URL requests (including folders) to the server. The Web.config file above is very cool:

1 It works on any IIS7 machine, you don't need an administrator to enable anything on the remote host, it can also work under the environment scenario of a shared host that is set to the Medium Trust security level (medium trusts).

2 because I have urlrewriter in the <modules> part of
IIS 7.0 will be released later this year as part of the Windows Longhorn Server and will support Go-live licensing with the release of BETA3 releases within a few weeks. Because of all the Shinjuku Primary (hosting) features added to IIS7, we expect the host vendor to start aggressively providing IIS7 accounts, which means you should soon be able to start using the above URL rewrite support without extensions. We will post a URL rewrite module for Microsoft in the IIS7 RTM session, which is free, you can use on IIS7, and this module will provide good support for advanced URL rewriting scenarios for all content on your Web server.

Sample Downloads: A sample application that I built using the IIS7 and urlrewriter.net modules to show no extension URL rewriting technology can be downloaded here.

Method Four: Use Isapirewrite in IIS5 and IIS6 to implement URL rewriting without extension
If you don't want to wait for IIS7 to come out and rewrite the URL without the extension, your best bet is to use the ISAPI filter to rewrite the URL. I know there are 2 ISAPI filter schemes that you might want to look at:

Helicon Tech ' s ISAPI Rewrite: They provide a 99 dollar (30 days free trial) ISAPI URL to rewrite the full version of the product, as well as a free lightweight version.
Ionic ' s ISAPI Rewrite: This can be downloaded for free (both source and executable files can be downloaded)
I have not personally used the above products, although I have heard of these 2 products praise. Scott Hanselman and Jeff Atwood have recently written wonderful blog posts about the experience of using these products, along with examples of how to configure matching rules in these products. The rules of the ISAPI rewrite of Helicon tech use the same syntax as the Apache mod_rewrite, for example (from Jeff's blog post):


[Isapi_rewrite]
# fix missing slash on folders
# Note, this is 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
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 the ISAPI modules and what you can do with them.

Note: One disadvantage of using ISAPI filters is that the shared hosting environment generally does not allow you to install such components, so if you want to use them, you either need a dedicated virtual host server or a dedicated host server. However, if you have a host program that allows you to install ISAPI, this will provide maximum flexibility under IIS5/6, allowing you to transition to the IIS7 rollout.

Dealing with asp.net postback in URL rewriting
One of the most common problems you encounter when using ASP.net and rewriting URLs is to deal with postback scenes. Specifically, when you place a < form runat= "Server" > Control on a Web page, ASP.net automatically points to the current page with the action attribute of the default output ID. When you use a URL rewrite, the problem occurs when the,<form> control displays a URL that is not the original requested URL (for example,/products/books), but rather a 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 originally made clean.

In ASP.net 1.0 and 1.1, people often resort to inheritance <form> control to generate their own controls to correctly output the action attribute to use. While this can work, the result is a bit messy because it means you need to update all of your pages to use this additional form control, and sometimes you will encounter problems with Visual studio WYSIWYG designer.

The good news is that in ASP.net 2.0, there's a clean trick you can use to override the <form> control's action attribute. Specifically, you can use the new ASP.net 2.0 control adapter extension architecture to customize the control's output, overwriting the value of the action attribute with the value you provide. This does not require any coding changes in your. aspx page, but simply add a. browser file to your/app_browsers folder and register to use a control fit class to output the new action attribute.




Here you can look at a sample implementation that I created that shows how to implement a form control adapter that works with the URL rewrite (form controls Adapter). It works in the first (request.pathinfo) that I use, and the second method (Urlrewriter.net module), which uses the Rawurl property of the Request to obtain a URL that was not previously overwritten. In the fourth method (Isapirewrite filter), you can get the original URL value that the ISAPI filter holds in request.servervariables["Http_x_rewrite_url".

My Formrewriter class implementation should work on the standard asp.net and asp.net AJAX 1.0 pages (let me know if you have a problem).

Handle CSS and image references correctly
Many people sometimes encounter a difficult illness when they first use a URL rewrite, and they find that their images and CSS stylesheet references sometimes stop working. This is because they have a relative reference to these files in an HTML page, and when you start rewriting URLs in your application, you need to realize that browsers often request files on different layers of logical hierarchies (logical hierarchy levels) rather than what is actually stored on the server.

For example, if the/products.aspx page above has a relative reference to the logo.jpg in the. aspx Web page, but is requested by/products/books.aspx this URL, the browser will issue a pair/ Products/logo.jpg the request, not the/logo.jpg request. To correctly refer to this file, make sure that you qualify (root qualify) CSS and image references ("/style.css" instead of "style.css") with the root directory. For ASP. NET control, you can also use the "~" syntax to refer to the file from the root directory you applied (for example, <asp:image imageurl= "~/images/logo.jpg" runat= "Server"/>).

I hope this article is of some help to you,

Scott
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.