Implementation principle and code example of ASP.net URL rewriting (URLRewriter)

Source: Internet
Author: User

ASP.net address rewriting (URLRewriter) implementation principle and code example Gao Lu I. Overview of visitor input: Unknown, Which is UrlRewrite, in addition to implementing the second-level domain name function, it plays an important role in simplifying user input addresses, SEO, and iterative website version updates. Microsoft once. net framework 1.1 provides a small tool named URLRewriter for developers to easily implement UrlRewrite, for: http://download.microsoft.com/download/0/4/6/0463611e-a3f9-490d-a08c-877a83b797cf/MSDNURLRewriting.msi this article takes URLRewriter as an example, in. net framework 2.0 environment has made a small part of optimization adjustments for your learning and reference, limited capabilities, please promptly point out the shortcomings. This document assumes that you have some knowledge about the Http pipelines of URLRewriter and ASP.net. Otherwise, please refer to relevant materials. 2. Configure URLRewriter to rewrite the URL in web. config using custom configuration and regular expression. Custom node declaration:

Custom node configuration items: ^ Http: // ([a-zA-Z0-9] {4, 16}) .cnblogs.com/default.aspx$ /$1/default. aspx ^ Http://www.cnblogs.com/([a-zA-Z0-9] {})/$ /Test/url. aspx? P = $1 As described above, I configured two rules to illustrate the instance, the first one can override: http://wu-jian.cnblogs.com to:/wu-jian/default. aspx second can override: http://www.cnblogs.com/wu-jian to:/test/url. aspx? P = wu-jian but Microsoft's URLRewriter LookFor does not support domain name location. It can only make a post after the root directory and cut a section of its source code DEMO: ~ /(\ D {4})/(\ d {2})/(\ d {2}) \. aspx ~ /ShowBlogContent. aspx? Year = $1 & month = $2 & day = $3 It can be found that URLRewriter does not support the use of second-level domain names or custom-level rewrite, so here I made a small part of the source code optimization, both matching and rewriting use the original expressions in LookFor and SendTo without any intelligent replacement or modification. In fact, in many cases, Microsoft products are able to find such a "Superfluous" shadow. Matching and replacement are actually based on the "reverse reference" Principle in the regular expression. In my blog, there are code examples. If you are not familiar with regular expressions, you can understand them, this is not detailed here. Iii. Class for accessing custom configurations through source code analysis: using System; using System. configuration; using System. xml; using System. xml. serialization; using System. xml. XPath; namespace PaoTiao. PTRewriter. config {///

/// Implement the IConfigurationSectionHandler interface to access custom nodes ///

Public class RewriterConfigSerializerSectionHandler: IConfigurationSectionHandler {///

/// This method does not need to be called. // It is stored in ConfigurationManager. when GetSection () is called, the configuration section processing class is automatically instantiated based on the class name and path defined in the configuration change section declaration ///

Public object Create (object parent, object configContext, System. xml. xmlNode section) {XmlSerializer ser = new XmlSerializer (typeof (RewriterConfiguration); return ser. deserialize (new XmlNodeReader (section); }}// end class} has been writing WEB programs and seldom uses custom nodes until Windows Service is written to the app at one time. config. To read custom nodes, you must implement the IConfigurationSectionHandler interface. Using System; using System. web; using System. web. caching; using System. configuration; using System. xml. serialization; namespace PaoTiao. PTRewriter. config {[Serializable ()] [XmlRoot ("RewriterConfig")] public class RewriterConfiguration {private RewriterRuleCollection rules ;///

/// This method reads the rule set from web. config and uses the Cache to avoid frequent IO operations ///

/// Public static RewriterConfiguration GetConfig () {// use the cache if (HttpContext. current. cache ["RewriterConfig"] = null) HttpContext. current. cache. insert ("RewriterConfig", ConfigurationManager. getSection ("RewriterConfig"); return (RewriterConfiguration) HttpContext. current. cache ["RewriterConfig"];} public RewriterRuleCollection Rules {get {return rules;} set {rules = value ;}}// end class} I want to use Url The vast majority of Rewrite websites are intended for public users. public users are faced with high traffic and concurrency, and no one wants to read the web for each request. config, so it is wise to use Cache here. In addition, the expired ConfigurationSettings. GetConfig () method is replaced by the ConfigurationManager. GetSection () method. The following two classes provide similar Model functions. Using System; using System. Collections; namespace PaoTiao. PTRewriter. Config {///

/// Rule set ///

[Serializable ()] public class RewriterRuleCollection: CollectionBase {///

/// Add a new rule to the set ///

/// RewriterRule object public virtual void Add (RewriterRule r) {this. InnerList. Add (r );}///

/// Get or set items ///

Public RewriterRule this [int index] {get {return (RewriterRule) this. innerList [index];} set {this. innerList [index] = value ;}}// end class} using System; namespace PaoTiao. PTRewriter. config {///

/// Data Object of the rewrite rule ///

[Serializable ()] public class RewriterRule {private string mLookFor; private string mSendTo ;///

/// Search for rules ///

Public string LookFor {get {return this. mLookFor;} set {this. mLookFor = value ;}}///

/// Rewrite the rule ///

Public string SendTo {get {return this. mSendTo;} set {this. mSendTo = value ;}}// end class} // end namespace use HttpModule to overwrite using System; using System. web; namespace PaoTiao. PTRewriter {///

/// Abstract class implementing IHttpModule ///

Public abstract class BaseModuleRewriter: IHttpModule {public virtual void Dispose () {} public virtual void Init (HttpApplication app) {app. beginRequest + = new EventHandler (this. baseModuleRewriter_BeginRequest);} protected virtual void BaseModuleRewriter_BeginRequest (object sender, EventArgs e) {HttpApplication app = (HttpApplication) sender; Rewrite (app );}///

/// Address rewriting abstract function ///

/// Protected abstract void Rewrite (HttpApplication app);} // end class} perform core logic processing in the Http module. The source code is in the AuthorizeRequest event, the BeginRequest event is used here. The Rewrite Implementation of the abstract method. You can find that URL rewriting is actually a core method: HttpContext. RewritePath. Let's take a look at the description of this method in MSDN: Specify the internal rewrite path and allow the requested URL to be different from the internal path of the resource. Using System; using System. Text. RegularExpressions; using System. Configuration; using System. IO; namespace PaoTiao. PTRewriter {public class ModuleRewriter: BaseModuleRewriter {///

/// Address rewriting function ///

/// Protected override void Rewrite (System. web. httpApplication app) {// start logging app. context. trace. write ("ModuleRewriter", "Entering ModuleRewriter"); // obtain the Config. rewriterRuleCollection rules = Config. rewriterConfiguration. getConfig (). rules; for (int I = 0; I <rules. count; I ++) {string lookFor = rules [I]. lookFor; Regex reg = new Regex (lookFor, RegexOptions. ignoreCase); if (reg. isMatch (app. request. url. toString () {// obtain the destination URL string sendToUrl = reg. replace (app. request. url. toString (), rules [I]. sendTo); // trace the log app. context. trace. write ("ModuleRewriter", "Rewriting URL to" + sendToUrl); // rewrite the app address. context. rewritePath (sendToUrl); // Temp code for debug // using (StreamWriter sw = new StreamWriter (@ "c: \ test \ rr.txt", true, System. text. encoding. UTF8) // {// sw. writeLine (app. request. url. toString (); // sw. writeLine ("------------------------------------"); // sw. close (); //} // exit for loop break;} // end tracking log app. context. trace. write ("ModuleRewriter", "Exiting ModuleRewriter") ;}// end class. register the custom Http module in config: 4. Apply back to the previous example, http://wu-jian.cnblogs.com -->/wu-jian/default. the position of aspx wu-jian is the domain name prefix, or a second-level domain name. This requires a wildcard resolution of * .cnblogs.com on the DNS. The second example is to resolve the directory to an address: http://www.cnblogs.com/wu-jian -->/test/url. aspx? P = wu-jian obviously, the key point here is how to let IIS handle requests in this format by the. net process. once it enters. net framwork, we will be able to do whatever we want. OK. You can perform the following operations: IIS Management --> site --> properties --> Home Directory tag --> Configuration --> wildcard application ing --> insert 1. Select C: \ WINDOWS \ Microsoft. NET \ Framework \ v2.0.50727 \ aspnet_isapi.dll 2. Do not check "check whether a file exists" 5. There are many introduction to Url Rewrite and many third-party components, such as isapi rewrite and iirf, they use the underlying interface of IIS to achieve higher efficiency. net in-process implementation is also a solution provided by Microsoft in the Framework1.1 era. In fact, this article was also written many years ago. It was just recently prepared to switch to IIRF and look at those. net Framework4.0 prompts that the method has expired, so I have to lament the time flow. I hope to help people who have spent time and energy in the past.

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.