在 ASP.NET 中执行 URL 重写

http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx?mfr=true

URLRewriter.cs


using System;
using System.Xml;
using System.Xml.XPath;
using System.Configuration;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Xml.Xsl;
using System.Web;

namespace JC.Web
{
 /// <summary>
 /// URLRewriter 的摘要说明。
 /// </summary>
 public class Rewriter : IConfigurationSectionHandler
 {
  protected XmlNode _oRules=null;

  protected Rewriter(){}

  public string GetSubstitution(string zPath)
  {
   Regex oReg;

   foreach(XmlNode oNode in _oRules.SelectNodes("rule"))
   {
    oReg=new Regex(oNode.SelectSingleNode("url/text()").Value);
    Match oMatch=oReg.Match(zPath);

    if(oMatch.Success)
    {
     return oReg.Replace(zPath,oNode.SelectSingleNode("rewrite/text()").Value);
    }
   }

   return zPath;
  }

  public static void Process()
  {
   Rewriter oRewriter=(Rewriter)ConfigurationSettings.GetConfig("system.web/urlrewrites");


   string zSubst=oRewriter.GetSubstitution(HttpContext.Current.Request.Path.ToLower());


   if(zSubst.Length>0)
   {
    HttpContext.Current.RewritePath(zSubst);
   }
  }

  #region Implementation of IConfigurationSectionHandler
  public object Create(object parent, object configContext, XmlNode section)
  {   
   _oRules=section;

   // TODO: Compile all Regular Expressions

   return this;
  }
  #endregion
 }

}


Web.Config

  <urlrewrites>
   
     <rule>
      <url>/default.html</url>
      <rewrite>/default.aspx</rewrite>
     </rule>
     
     <rule>
      <url>/products.html</url>
      <rewrite>products/products.aspx</rewrite>
     </rule>
     
     <rule>
      <url>/axblog.html</url>
      <rewrite>blog/blog.aspx?cid=2</rewrite>
     </rule>
     <rule>
      <url>/blog/a(\d+).html</url>
      <rewrite>/blog/blogdetail.aspx?aid=$1</rewrite>
     </rule>
     <rule>
      <url>/blog/cid(\d+).html</url>
      <rewrite>/blog/blog.aspx?cid=$1</rewrite>
     </rule>
     <rule>
      <url>/blog/c(\d+)a(\d+).html</url>
      <rewrite>/blog/blogdetail.aspx?cid=$1&amp;aid=$2</rewrite>
     </rule>
     <rule>
      <url>/blog/dt(\d+).html</url>
      <rewrite>/blog/blog.aspx?dt=$1</rewrite>
     </rule>
     <rule>
      <url>/support/faq_cid(\d+).html</url>
      <rewrite>/support/faqlist.aspx?cid=$1</rewrite>
     </rule>
      <rule>
      <url>/support/faq_c(\d+)a(\d+).html</url>
      <rewrite>/support/faqdetail.aspx?cid=$1&amp;aid=$2</rewrite>
     </rule>

     <rule>
      <url>(.+)\.html</url>
      <rewrite>$1.aspx</rewrite>
     </rule>    
     
  </urlrewrites>


Global

  protected void Application_BeginRequest(Object sender, EventArgs e)
  {
   JC.Web.Rewriter.Process();     
  }

posted on 2007-04-16 17:13  jinchun  阅读(228)  评论(0编辑  收藏  举报