Introduction to the implementation of URL Rewrite in ASP. NET MVC

Source: Internet
Author: User

This article will show you how to use ASP. net mvc uses IIS-level URL Rewrite. Although this method is not widely used, it also plays a role. BKJIA editor recommends ASP. net mvc Framework video tutorial.

About a year and a half ago, I wrote a series of articles on URL Rewrite 2, 3, and 4 on my blog. the URL Rewrit method and their respective features are described in detail on the. NET platform. It should be said that what we have already talked about is very specific. We can deal with 90% of the cases. In fact, the principle of IIS Rewrite is very easy to understand. After some simple changes and inferences, you can get the cause and solution of some problems. Now let's look at a real case: using IIS-level URL Rewrite in ASP. net mvc.

In my post at that time, I mentioned that URL Rewrite has two levels: IIS level and ASP. NET level, and each has its own characteristics and restrictions. In ASP. net mvc is commonly used in ASP. NET-level URL Routing. Its function is to capture data from the URL and hand it over to the program for use. Of course, there is also the "constructor" function. Let's talk about it later ). Therefore, ASP. net mvc usually does not require ASP. NET-level URL Rewrite. Nowadays, the IIS-level URL Rewrite can be avoided because of some special problems.

The URLs involved in the following take http://51programming.com as an example, this domain name has been pan-resolved to 127.0.0.1, if you need it can be used to experiment.

Many years ago, the Path of a URL was a normal Path, and dynamic parameters, such as the Query Path, were provided through Query String. For example:

Http://51programming.com/products? Keywords = helloworld to avoid confusion, let's clarify some concepts here. What is URL, Path, and QueryString. For example, the preceding addresses are:

 
 
  1. URL:http://51programming.com/products?keywords=helloworld   
  2. Path:http://51programming.com/products   
  3. Query String:keywords=helloworld 

After the rise of SEO, some people said that such "Dynamic Address" is not conducive to the weight optimization in the search engine, so it is recommended to use keywords as part of the Path. The following URL is displayed:

Bytes. For example, if you enter "200%" as the keyword, the URLs in the two forms are:

Http://51programming.com/products? Keywords = 200% 25
Pipeline Request exception:

This is because the Path part of the URL contains special characters, which can only appear in the Query String.

What information do you realize when you see this picture? When locating the cause of the problem and trying to solve the problem, we must first determine where the problem occurred. For example, when you see this picture, you should be aware that this is ASP. NET exception. In other words, IIS does not regard it as an invalid URL. It still honestly handed over the URL to ASP.. net isapi processing. Therefore, we can use IIS-level URL Rewrite to replace the URL with an acceptable form before entering the ASP. NET execution engine:

RewriteRule ^/products/([^ \?] *)\? (. +)/Products? $2 & keywords = $1 [I, L, U]

RewriteRule ^/products/([^ \?] *)/Products? Keywords = $1 [I, L, U] The first line deals with Query strings, while the second line does not. The component used here is IIRFIonic's Isapi Rewrite Filter). This is an open-source product. This is also recommended in my article a year and a half ago. Now it has been upgraded. Its function is to rewrite the URL to another form before entering ASP. net isapi:

The Bad Request that will appear in step 1 is already in the valid format of URL Rewrite in step 2. Therefore, there is no problem with the remaining processing.

These contents have been mentioned in the article a year and a half ago, but now that ASP. net mvc is available, things become more complicated. ASP. NET Routing is not only responsible for URL matching, but also for URL assembly. Therefore, it is not difficult for ASP. NET Routing to identify the URL after Rewrite, but it requires some tips to make it "Assemble" the URL before Rewrite. For example, the following Route configuration can only identify URL input/products? Keywords = xxx) but cannot assemble the required URL/products/xxx ):

 
 
  1. routes.MapRoute(  
  2.     "Product.List",  
  3.     "products",  
  4.     new { controller = "Product", action = "List" }); 

Therefore, we must do this:

 
 
  1. routes.MapRoute(  
  2.     "Product.List",  
  3.     "products/{*keywords}",  
  4.     new { controller = "Product", action = "List", keywords = "" }); 

Please note that we allow keywords to match all the content at the backend of the Path, and because we provide the default value of keywords, even the Path input such as "/products, this Route rule can be correctly matched. However, the keywords field in the Route Value is no longer the content entered by the user. Because the/products/xxx entered by the user has been rewritten as/products? Keywords = xxx ). In other words, if there is an Action as follows, Its keywords parameter will always be a Null String:

Public ActionResult List (string keywords) {...} fortunately, the Model Binder mechanism exists in ASP. net mvc. We can compile a Model Binder to specify the location for obtaining this parameter:

 
 
  1. public class FromQueryBinder : IModelBinder  
  2. {  
  3.     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)  
  4.     {  
  5.         return controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];  
  6.     }  

Then apply it to the keywords parameter of the List:

 
 
  1. public ActionResult List(  
  2.     [ModelBinder(typeof(FromQueryBinder))]string keywords) 

Because the parameter name is keywords, bindingContext. ModelName is also keywords, so we can get the required content from the Query String. As for URL generation, we can add a keywords field to Route Value in the same way, therefore, in the previously configured Route rule, it will be assembled into a proper Path, namely/products/xxx ).

In this example, we allow keywords to match all the content in the backend of the Path. But what if a specific section in the Path requires special characters? In fact, the same is true, but when performing URL Rewrite, you need to enter a "false" value during the final Rewrite, such as the Route rule:

 
 
  1. routes.MapRoute(  
  2.     "Product.List",  
  3.     "products/{keywords}/page",  
  4.     new { controller = "Product", action = "List" }); 

The IIS-level URL Rewrite rules can be:

RewriteRule ^/products/([^/] *)/(. *)/products/useless-segement/$2? Keywords = $1 [I, L, U]. If the user inputs/products/xxx/2, it will be rewritten to/products/useless-token/2? Keywords = xxx -- in fact, we can do the same in the first example, but I am not used to adding a forged value.

The above solution can be used normally in the Classic Mode of IIS 6 and IIS 7, but unfortunately in the Intergrated Mode of IIS 7, it may be caused by ASP. NET takes over part of the IIS logic, so it will throw "IIS level" very early, instead of "ASP. NET-level Bad Request exception. If you encounter this problem, you must take the following three steps to solve the problem:

Set AllowRestrictedChars: KB820129 to make IIS 7 accept special characters)

Setting VerificationCompatibility: steps other than "Install. NET 1.1 SP1" in kb88.0 allow ASP. NET to accept special characters)

Set ValidateRequest of the ASP. NET page to False.

In fact, you only need to modify these three steps. In this case, there is no problem even if you do not need IIS-level URL Rewrite.

This article is from Zhao Yi's blog garden article "using IIS-level URL Rewrite in ASP. net mvc"

  1. Detailed description of ASP. net mvc paging Implementation Method
  2. Differences between ASP. net mvc and WebForm
  3. ASP. net mvc application Execution Process Analysis
  4. Implementation of ASP. net mvc paging controls
  5. Some basic knowledge about ASP. net mvc Framework

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.