利用IHttpModule实现ASP.NET URL重写

IHttpModule接口实现类OwnHttpModule:

using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Collections.Generic;

/// <summary>
///IHttpModule接口实现类
/// </summary>
public class OwnHttpModule : IHttpModule
{
    #region IHttpModule 成员

    /// <summary>
    /// 初始化模块,并使其为处理请求做好准备
    /// </summary>
    /// <param name="app"></param>
    public void Init(HttpApplication app)
    {
        app.AuthorizeRequest += delegate(object sender, EventArgs e)
        {
            HttpApplication app2 = (HttpApplication)sender;
            Rewrite(app2.Request.Path, app2);
        };
    }

    /// <summary>
    /// 处置由实现 System.Web.IHttpModule 的模块使用的资源(内存除外)
    /// </summary>
    public void Dispose() { }

    #endregion

    #region URL 重写

    /// <summary>
    /// URL 重写
    /// </summary>
    /// <param name="requestedPath"></param>
    /// <param name="app"></param>
    protected void Rewrite(string requestedPath,System.Web.HttpApplication app)
    {
        //这边为方便演示直接往集合添加规则,实际应用可考虑将规则写到配置文件中再读取
        Dictionary<string, string> rules = new Dictionary<string, string>();
        rules.Add(@"^/news/(\w+)\.aspx", "/news.aspx?t=$1");
        rules.Add(@"^/soft/(\w+)\.aspx", "/soft.aspx?t=$1");
        rules.Add(@"^/music/(\w+)\.aspx", "/music.aspx?t=$1");

        foreach (KeyValuePair<string, string> rule in rules)
        {
            Match match = Regex.Match(app.Context.Request.Path, rule.Key, RegexOptions.IgnoreCase);
            if (match.Success)
            {
                string sendToUrl = Regex.Replace(app.Context.Request.Path,rule.Key,rule.Value, RegexOptions.IgnoreCase);
                string path = sendToUrl;//虚拟路径
                string querystring = string.Empty;//查询参数
                if(sendToUrl.IndexOf("?") != -1)
                {
                    path = sendToUrl.Substring(0,sendToUrl.IndexOf("?"));
                    querystring = sendToUrl.Substring(sendToUrl.IndexOf("?") + 1);
                }

                app.Context.RewritePath(path, string.Empty, querystring);

                return;
            }
        }
    }

    #endregion
}

使用非常简单,只需在配置文件web.config的<system.web>节点中加入下边节点即可:

<httpModules>
  <add type="OwnHttpModule" name="URLRewriter" />
</httpModules>

说明:Http模块必须是IIS将请求调度给 aspnet_isapi.dll ISAPI 扩展后才能发挥作用,所以要使http://www.mzwu.com/news类似的URL能正确重写,必须保证news文件下有default.aspx文件,其原理是访问该URL时,IIS搜索到默认首页文件default.aspx后才会把请求调度给 aspnet_isapi.dll ISAPI 扩展,Http模块才能发挥作用。

参考文章

[1].在ASP.NET中执行URL重写:http://msdn.microsoft.com/zh-cn/library/ms972974.aspx

评论: 0 | 引用: 0 | 查看次数: 5079
发表评论
登录后再发表评论!