Rewrite URL code in ASP. NET

Source: Internet
Author: User

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) handle this situation: you need to change the structure of the web page in your web application, but you also need to ensure 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) Improve the search relevance of web pages on your website in search engines such as Google, Yahoo, and Live. 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 a fully qualified URL, you can also improve the priority of your search engine results in some situations. Use the same case (same case) and URL entry to force referring links (for example, using weblogs.asp.net/scottgu instead of weblogs.asp.net/scottgu/default.aspx) technology can also avoid page ranking (pagerank) caused by crossing 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) technologies to optimize their websites (note, SEO is a fast-paced space, it is recommended that you increase the relevance of your search ). I suggest you read "SSW Rules to Better Google Rankings (essentials for improving Google ranking by SSW)" if you want to know some good suggestions on search engine optimization. and MarketPosition articles about how URLs can affect top search engine ranking (how does a URL affect top 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. the/parameter value after the aspx web page processor name appears. Then, an automated search engine crawler will interpret these URLs into three different URLs, rather than 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. This attribute returns the part of the URL following products. aspx. Therefore, for the above URLs, Request. pathInfo returns "/Books", "/DVDs", and "/CDs" respectively (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 ). By using the RewritePath method of HttpContext, We can dynamically rewrite the received URL to a single Products when these requests enter the server. the aspx web page accepts 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 hard writing each URL in the web. config 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. This technology works well in a shared host environment that is set to a medium trust (medium trust) (you only need to copy the file FTP/XCOPY to a remote server, ).

Method 3: Use HttpModule in IIS7 to rewrite a URL without an extension
The above HttpModule method works when the URL you want to override contains the. aspx extension or another 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 an extension (for example,. jpg,. gif, or. htm) that is not processed by ASP. NET, or has 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. IIS 5/6 makes it 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 to rewrite the IIS request pipeline (request pipeline) earlier. 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 now 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. asp ,. php, or. jsp extension URL ). 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 trust) in the shared host environment.

2) Because I have configured UrlRewriter in the
IIS 7.0 will be released later this year as part of the Windows Longhorn server. It 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 release a URL rewriting module supported by Microsoft in IIS7 RTM. 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) full version of the isapi url Rewrite product, and 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 both recently wrote wonderful blog posts about how to use these products and provided examples of how to configure matching rules in these products. The ISAPI Rewrite Rules of Helicon Tech use the same syntaxes 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
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 on a webpage, ASP. NET automatically points the action attribute of the output identifier to the current page by default. This problem occurs when URL rewriting is used. The <form> Control shows that the URL is not the original requested URL (for example,/products/books ), instead, the 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, you often resort to inheriting the <form> controls to generate their own controls to correctly output the action attributes to be used. Although this works, the results are messy, because it means you need to update all your pages to use this other form control, and sometimes there are problems in the WYSIWYG designer in Visual Studio.

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 control adapter extension architecture to customize the control output and overwrite the value of the action property with the value you provide. This is not required in your. make any encoding changes on the aspx page, and add one in your/app_browsers folder. browser file, register and use a control adaptation class to output new action attributes.




You can view a sample implementation that I created here, which shows how to implement the Form Control Adapter (Form Control Adapter) that cooperates with URL rewriting ). The first Request. pathInfo), the second method (UrlRewriter.. Net module), it uses the RawUrl attribute of the Request to obtain the URL that has not been rewritten for display. In the fourth method (ISAPIRewrite filter), you can obtain the original URL value of the ISAPI filter stored in Request. ServerVariables ["HTTP_X_REWRITE_URL.

The FormRewriter class above should work on standard ASP. NET and ASP. net ajax 1.0 web pages (if you have any problems, let me know ).

Correctly process CSS and image references
When using URL rewriting for the first time, many people sometimes encounter a difficult problem, that is, they find that their images and CSS style sheet references sometimes stop working. This is because they have relative references to these files on HTML pages. When you start to rewrite the URL in the application, you need to realize that browsers often request files at different logical hierarchy levels layers, rather than what is actually stored on the server.

For example, if the/products. aspx webpage. the logo.jpg file in the aspx webpage has a relative reference, but it is referenced by/products/books. when the browser displays a webpage, it will send a request to/products/logo.jpg instead of/logo.jpg. To reference this file correctly, make sure that you use the root directory to restrict (root qualify) CSS and image reference ("/style.css" instead of “style.css "). For ASP. NET controls, you can also use "~" Syntax reference a file from the root directory of your application (for example, <asp: image imageurl = "~ /Images/logo.jpg "runat =" server "/> ).

I hope this article will help 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.