url重写类介绍

  让我们先介绍一下 Web.config 文件中重写规则的结构。首先,您需要在 Web.config 文件中指明要使用 HTTP 模块还是 HTTP 处理程序来执行 URL 重写。在下载代码中,Web.config 文件包含两个已注释掉的条目:

<!--
<httpModules>
   <add type="URLRewriter.ModuleRewriter, URLRewriter" 
        name="ModuleRewriter" />
</httpModules>
-->

<!--
<httpHandlers>
   <add verb="*" path="*.aspx" 
        type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>
-->

在 Web.config 文件中:

<RewriterConfig>
   <Rules>
   <RewriterRule>
      <LookFor>要查找的模式</LookFor>
      <SendTo>要用来替换模式的字符串</SendTo>
   </RewriterRule>
   <RewriterRule>
      <LookFor>要查找的模式</LookFor>
      <SendTo>要用来替换模式的字符串</SendTo>
   </RewriterRule>
   ...
   </Rules>
</RewriterConfig>
public abstract class BaseModuleRewriter : IHttpModule
{
   public virtual void Init(HttpApplication app)
   {
      // 警告!此代码不适用于 Windows 身份验证!
      // 如果使用 Windows 身份验证,
      // 请改为 app.BeginRequest
      app.AuthorizeRequest += new 
         EventHandler(this.BaseModuleRewriter_AuthorizeRequest);
   }

   public virtual void Dispose() {}

   protected virtual void BaseModuleRewriter_AuthorizeRequest(
     object sender, EventArgs e)
   {
      HttpApplication app = (HttpApplication) sender;
      Rewrite(app.Request.Path, app);
   }

   protected abstract void Rewrite(string requestedPath, 
     HttpApplication app);
}
protected override void Rewrite(string requestedPath, 
   System.Web.HttpApplication app)
{
   // 获得配置规则
   RewriterRuleCollection rules = 
     RewriterConfiguration.GetConfig().Rules;

   // 遍历每个规则...
   for(int i = 0; i < rules.Count; i++)
   {
      // 获得要查找的模式,并且
      // 解析 Url(转换为相应的目录)
      string lookFor = "^" + 
        RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, 
        rules[i].LookFor) + "___FCKpd___3quot;;

      // 创建 regex(请注意,已设置 IgnoreCase...)
      Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);

      // 查看是否找到了匹配的规则
      if (re.IsMatch(requestedPath))
      {
         // 找到了匹配的规则 -- 进行必要的替换
         string sendToUrl = 
RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, 
            re.Replace(requestedPath, rules[i].SendTo));

         // 重写 URL
         RewriterUtils.RewriteUrl(app.Context, sendToUrl);
         break;      // 退出 For 循环
      }
   }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值