UrlRewrite (URL rewriting) -- Implementation in ASP. NET,

Source: Internet
Author: User

UrlRewrite (URL rewriting) -- Implementation in ASP. NET,
Overview

Today I saw the implementation of URL rewriting, mainly focusing on URL Rewrite in MS.

The advantages of URL rewriting include: more friendly URLs and support for old versions of URLs

The main disadvantage of URL rewriting is: poor performance, because if you want to support URLs without a suffix (but more often we need to support this method) you must configure all URLs (including js, css, and image) in IIS to be forwarded to the aspnet_isapi. For the solution, see use URL rewriting with caution. Another performance problem is that, based on the source code, when matching a url, use a regular expression to try to match each rule until one or both matches are successful. For URLs that do not need to be rewritten, all the regular expressions must be executed once. You can make a judgment before entering the match to eliminate some situations.

1. Configure web. config

1.1 download MS URLRewrite

Address: http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi

1.2 configure the Declaration node for the custom section

  <configSections>    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />  </configSections>

1.3 configure the content of the custom section

After UrlRewrite is configured, the main task is to write the regular expression for configuring url ing. For those who are not clear about the regular expression, you can take a look at the regular expression entry and memo.

  <RewriterConfig>    <Rules>      <RewriterRule>        <LookFor>~/pick/?</LookFor>        <SendTo><![CDATA[~/pick.aspx]]></SendTo>      </RewriterRule>      <RewriterRule>        <LookFor>~/pick/(\d+)</LookFor>        <SendTo><![CDATA[~/pick.aspx?page=$1]]></SendTo>      </RewriterRule>      <RewriterRule>        <LookFor>~/(\w+)/p/(\d+).html</LookFor>        <SendTo><![CDATA[~/BlogDetails.aspx?blogwriter=$1&blogid=$2]]></SendTo>      </RewriterRule>      <RewriterRule>        <LookFor>~/Product/(\w{4}).html</LookFor>        <SendTo>~/Product.aspx?id=$1</SendTo>      </RewriterRule>    </Rules>  </RewriterConfig>

1.4 configure httpmodules or httphandlers

In the case of the old IIS 6.0, you can configure httpmodules and httphandlers under the <system. web> node to intercept all requests.

    

In the new IIS7.0, configured under the <system. webServer> node, modules and handlers only need one

  <system.webServer>    <modules>      <add type="URLRewriter.ModuleRewriter, URLRewriter" name="ModuleRewriter" />    </modules>    <!--

1.5 configure IIS

After publishing to IIS, if an error occurs in the access path, you need to map the extension. No error is reported for the IIS7.0 I use. You can directly access it.

2. Code Analysis

The source code of UrlRewrite is very simple. In fact, it implements an IHttpModule interface to intercept all request URLs. Then, use a regular expression to match the request URL with each other until a match is successful. Then, convert the original url (false) to the actual url based on the regular expression. If none of them match, the request will be processed based on the original path.

The main code is

Protected override void Rewrite (string requestedPath, System. web. httpApplication app) {// log information to the Trace object. app. context. trace. write ("ModuleRewriter", "Entering ModuleRewriter"); // get the configuration rules RewriterRuleCollection rules = RewriterConfiguration. getConfig (). rules; // iterate through each rule... for (int I = 0; I <rules. count; I ++) {// get the pattern to look fo R, and Resolve the Url (convert ~ Into the appropriate directory) string lookFor = "^" + RewriterUtils. resolveUrl (app. context. request. applicationPath, rules [I]. lookFor) + "$"; // Create a regex (note that IgnoreCase is set ...) regex re = new Regex (lookFor, RegexOptions. ignoreCase); // See if a match is found if (re. isMatch (requestedPath) {// match found-do any replacement needed string sendToUrl = RewriterUtils. resolveUrl (app. context. request. applicationPath, re. replace (requestedPath, rules [I]. sendTo); // log rewriting information to the Trace object app. context. trace. write ("ModuleRewriter", "Rewriting URL to" + sendToUrl); // Rewrite the URL RewriterUtils. rewriteUrl (app. context, sendToUrl); break; // exit the for loop} // Log information to the Trace object app. context. trace. write ("ModuleRewriter", "Exiting ModuleRewriter ");}View Code

After reading the source code, I also learned something on the web. configure a custom node, and then implement the IConfigurationSectionHandler interface to convert the section content into an object. The main code is as follows:

Public static RewriterConfiguration GetConfig () {if (HttpContext. current. cache ["RewriterConfig"] = null) HttpContext. current. cache. insert ("RewriterConfig", ConfigurationManager. getSection ("RewriterConfig"); return (RewriterConfiguration) HttpContext. current. cache ["RewriterConfig"];} // <summary> // Deserializes the markup in Web. config into an instance of the <see cref = "RewriterConfiguration"/> class. /// </summary> public class RewriterConfigSerializerSectionHandler: IConfigurationSectionHandler {// <summary> // Creates an instance of the <see cref = "RewriterConfiguration"/> class.: IConfigurationSectionHandler // </summary> // <remarks> Uses XML Serialization to deserialize the XML in the Web. config file into an // <see cref = "RewriterConfiguration"/> instance. </remarks> // <returns> An instance of the <see cref = "RewriterConfiguration"/> class. </returns> public object Create (object parent, object configContext, System. xml. xmlNode section) {// Create an instance of XmlSerializer based on the RewriterConfiguration type... xmlSerializer ser = new XmlSerializer (typeof (RewriterConfiguration); // Return the Deserialized object from the Web. config XML return ser. deserialize (new XmlNodeReader (section ));}}View Code3 final

Finally, although UrlReWrite is easy to use, but according to the source code, the performance problem is a big one, but it is still normal to use your own small website, if the request is large, we also know that there is a problem with UrlRewrite. You can use httphander to intercept only specific URLs, or use IIS filter (I have never done it, but it should be usable, after all, it intercepts most requests on the IIS side, rather than placing the requests in the Extended Program ). For IIS filter, refer to this article to execute URL rewriting in ASP. NET.

 

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.