Tip/tip: rewrite the URL in ASP. NET)

Source: Internet
Author: User

Tip/tip: rewrite a URL in ASP. NET

[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) 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 about how URLs can affect top search engine ranking (how does a URL affect top search engine ranking)Article.

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>


requirepermission = "false"
type = "intelligencia. urlrewriter. configuration. rewriterconfigurationsectionhandler, intelligencia. urlrewriter "/>





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