URL ing 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.

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.

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 "):

 
 
  1. FunctionGetCategory()AsString  
  2. If(Request.PathInfo.Length=0)Then  
  3. Return""  
  4. Else  
  5. ReturnRequest.PathInfo.Substring(1)  
  6. EndIf  
  7. EndFunction 

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.

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:

 
 
  1. voidApplication_BeginRequest(objectsender,EventArgse){  
  2. stringfullOrigionalpath=Request.Url.ToString();  
  3. if(fullOrigionalpath.Contains("/Products/Books.aspx")){  
  4. Context.RewritePath("/Products.aspx?Category=Books");  
  5. }  
  6. elseif(fullOrigionalpath.Contains("/Products/DVDs.aspx")){  
  7. Context.RewritePath("/Products.aspx?Category=DVDs");  
  8. }  


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 ):

 
 
  1. <?xmlversionxmlversion="1.0"?> 
  2. <configuration> 
  3. <configSections> 
  4. <sectionnamesectionname="rewriter" 
  5. requirePermission="false" 
  6. type="Intelligencia.UrlRewriter.Configuration.
    RewriterConfigurationSectionHandler,Intelligencia.UrlRewriter"/> 
  7. </configSections> 
  8. <system.web> 
  9. <httpModules> 
  10. <addnameaddname="UrlRewriter"type="Intelligencia.UrlRewriter.
    RewriterHttpModule,Intelligencia.UrlRewriter"/> 
  11. </httpModules> 
  12. </system.web> 
  13. <rewriter> 
  14. <rewriteurlrewriteurl="~/products/books.aspx"to="~/products.aspx?category=books"/> 
  15. <rewriteurlrewriteurl="~/products/CDs.aspx"to="~/products.aspx?category=CDs"/> 
  16. <rewriteurlrewriteurl="~/products/DVDs.aspx"to="~/products.aspx?category=DVDs"/> 
  17. </rewriter> 
  18. </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:

 
 
  1. <rewriter> 
  2. <rewriteurlrewriteurl="~/products/(.+).aspx"to="~/products.aspx?category=$1"/> 
  3. </rewriter> 

This makes your code extremely clean and scalable.

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, ). The above describes URL ing in ASP. NET.

  1. Brief Introduction to ASP applications
  2. IScriptControl of ASP. NET
  3. ASP. NET Authentication Service
  4. Overview ASP. NET Security
  5. ASP. NET ISAPI

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.