ASP.NET 实现 URL 重写的方法

 通过 Global.asax 实现重写,可以将重写的配置信息保存到 Web.config 中,也可以定义自己的配置文件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/// <summary>
/// 初始化重写模块。
/// </summary>
/// <param name="app">应用程序对象。</param>
public void Init(HttpApplication app)
{
    //RoutingSection section =
    //    (RoutingSection)ConfigurationManager.GetSection("routeConfiguration");
    //if (null == section)
    //{
    //    throw new Exception("还没有配置你的 Route 规则,请配置你的 Route 规则");
    //}
    //if (RouteTable.Routes.Count == 0)
    //{
    //    RouteTable.Routes.RegisterRoutes(section);
    //}
    //app.BeginRequest += new EventHandler(this.RewriteBeginRequest);
    //app.BeginRequest += new EventHandler(this.SessionStart);
    RegisterRoutes(RouteTable.Routes);
}     
/// <summary>
/// 使用指定路径重写 URL,并处理 URL 参数。
/// </summary>
/// <param name="context"></param>
/// <param name="sendToUrl"></param>
protected void RewritePath(HttpContext context, string sendToUrl)
{
    if (context.Request.QueryString.Count > 0)
    {
        if (sendToUrl.IndexOf('?') != -1)
        {
            sendToUrl += "&" + context.Request.QueryString.ToString();
        }
        else
        {
            sendToUrl += "?" + context.Request.QueryString.ToString();
        }
    }
    string queryString = String.Empty;
    string sendToUrlLessQString = sendToUrl;
    if (sendToUrl.IndexOf('?') > 0)
    {
        sendToUrlLessQString = sendToUrl.Substring(0, sendToUrl.IndexOf('?'));
        queryString = sendToUrl.Substring(sendToUrl.IndexOf('?') + 1);
    }
    context.RewritePath(sendToUrlLessQString, String.Empty, queryString);
}
/// <summary>
/// 处理各种路径
/// </summary>
/// <param name="appPath"></param>
/// <param name="url"></param>
/// <returns></returns>
public string ResolveUrl(string appPath, string url)
{
    //   return url;
    if (url.Length == 0 || url[0] != '~')
        return url;        // there is no ~ in the first character position, just return the url
    else
    {
        if (url.Length == 1)
            return appPath;  // there is just the ~ in the URL, return the appPath
        if (url[1] == '/' || url[1] == '\\')
        {
            // url looks like ~/ or ~\
            if (appPath.Length > 1)
                return appPath + "/" + url.Substring(2);
            else
                return "/" + url.Substring(2);
        }
        else
        {
            // url looks like ~something
            if (appPath.Length > 1)
                return appPath + "/" + url.Substring(1);
            else
                return appPath + url.Substring(1);
        }
    }
}
 
#region Url Rewrite...
/// <summary>
/// 开始重写。
/// </summary>
/// <param name="sender">应用程序对象。</param>
/// <param name="e">事件对象。</param>
private void RewriteBeginRequest(object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
    //初始化 Url 重写规则。
    Dictionary<string, string> urlRewrite = CacheProvider.GetRewrite();
    foreach (KeyValuePair<string, string> urlRule in urlRewrite)
    {
        // string lookFor = ResolveUrl(app.Request.ApplicationPath, urlRule.Key);
        string lookFor = "^" + ResolveUrl(app.Request.ApplicationPath, urlRule.Key) + "$";
        Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
        if (re.IsMatch(app.Request.Path))
        {
            string sendTo = ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(app.Request.Path, urlRule.Value));
            RewritePath(app.Context, sendTo);
        }
        //if (!string.IsNullOrEmpty(urlRewrite) && !string.IsNullOrEmpty(urlRule.Key))
        //{
        //    if (Regex.IsMatch(urlRewrite, urlRule.Key, RegexOptions.IgnoreCase))
        //    {
        //        return Regex.Replace(urlRewrite, urlRule.Key, urlRule.Value, RegexOptions.IgnoreCase);
        //    }
        //}
    }
    //if (!string.IsNullOrEmpty(urlRewrite))
    //{
    //    app.Context.RewritePath(urlRewrite);
    //}
}
#endregion   

  

posted @   Charles Zhang  阅读(5035)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示