让我们先介绍一下 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 循环 } } }