方法二:使用HttpModule实现URL重写

上述Request.PathInfo技术的替换方法是,利用ASP.NET提供的HttpContext.RewritePath方法。这个方法允许开发人员动态地重写收到的URL的处理路径,然后让ASP.NET使用刚重写过后的路径来继续执行请求。

譬如,我们可以选择向大众呈示下列URL:

http://www.store.com/products/Books.aspx
http://www.store.com/products/DVDs.aspx
http://www.store.com/products/CDs.aspx

在外界看来,网站上有三个单独的网页(对搜索爬虫而言,这看上去很棒)。通过使用 HttpContext的RewritePath方法,我们可以在这些请求刚进入服务器时,动态地把收到的URL重写成单个Products.aspx网 页接受一个查询字符串的类别名称或者PathInfo参数。譬如,我们可以使用Global.asax中的 Application_BeginRequest事件,来这么做:

    void Application_BeginRequest(object sender, EventArgs e) {

        string fullOrigionalpath = Request.Url.ToString();
        
         if (fullOrigionalpath.Contains("/Products/Books.aspx")) {
             Context.RewritePath("/Products.aspx?Category=Books");
        }
        else if (fullOrigionalpath.Contains("/Products/DVDs.aspx")) {
             Context.RewritePath("/Products.aspx?Category=DVDs");
        }
     }

手工编写象上面这样的编码的坏处是,很枯燥乏味,而且容易犯错。我建议你别自己写,而是使用网上现成的HttpModule来完成这项工作。这有几个你现在就可以下载和使用的免费的HttpModule:

这些模块允许你用声明的方式在你应用的web.config文件里表达匹配规则。譬如,在你应用的web.config文件里使用UrlRewriter.Net模块来把上面的那些URL映射到单个Products.aspx页上,我们只要把这个web.config文件添加到我们的应用里去就可以了(不用任何编码):

<?xml version="1.0"?>

<configuration>

  <configSections>
    <section name="rewriter"  
              requirePermission="false"
              type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
   </configSections>
  
  <system.web>
      
    <httpModules>
      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter"/>
     </httpModules>
    
  </system.web>

  <rewriter>
    <rewrite url="~/products/books.aspx" to="~/products.aspx?category=books" />
     <rewrite url="~/products/CDs.aspx" to="~/products.aspx?category=CDs" />
     <rewrite url="~/products/DVDs.aspx" to="~/products.aspx?category=DVDs" />
   </rewriter>  
  
</configuration>

上面的HttpModule URL重写模块还支持正则表达式和URL模式匹配(以避免你在web.config 文件里硬写每个URL)。所以,不用写死类别名称,你可以象下面这样重写匹配规则,把类别名称动态地从任何/products/[类别].aspx组合的 URL里取出来:

  <rewriter>
    <rewrite url="~/products/(.+).aspx" to="~/products.aspx?category=$1" />
   </rewriter>  

这使得你的编码极其干净,并且扩展性非常之好。

样例下载:我建立的一个使用UrlRewriter.Net模块展示这个技术的样例应用可以在这里下载

这个样例和这个技术的很好的地方在于,为部署使用这个方法的ASP.NET应用,不需作任何服务器配置改动。在设置为中等信任安全等级 (medium trust)的共享主机的环境里,这个技术也行之有效 (只要把文件FTP/XCOPY到远程服务器就可以了,不需要安装)。

Posted on 2008-11-02 21:58  Yongming Ye  阅读(162)  评论(0)    收藏  举报