在Url重写的很多方案中,都用到了正则,在页面比较少的情况下,可能看不出什么问题
但页面一旦过多,正则的性能凸显,这里给出一个不需要试用正则的方案,当然了,不用正则就需要遵守一些约定
我这里定制了一个规则,一个Url由4部分组成:页面路径信息 + 分隔符 + 参数列表 + Url后缀
给个例子:Home/q/id/1/cata/2/name/icecoffee.aspx
页面路径信息 = Home
分隔符 = /q/
参数列表 = id/1/cata/2/name/icecoffee
Url后缀 = .aspx
我标红的部分,是可配置的,好了,废话不多说,直接上代码- public class UrlRouteModule : IHttpModule
- {
- private static string URL_FLAG = "/q/"; //Url中区别路径和参数的分隔符
- private static string URL_SUFFIX = ".aspx"; //对哪种后缀的Url实施Rewrite
- public void Init(HttpApplication context)
- {
- context.BeginRequest += new EventHandler(context_BeginRequest);
- }
- private void context_BeginRequest(object sender, EventArgs e)
- {
- HttpApplication app = sender as HttpApplication;
- if (app == null) return;
- string currentUrl = app.Context.Request.RawUrl;
- if (currentUrl.EndsWith(URL_SUFFIX, StringComparison.OrdinalIgnoreCase) == false) //后缀不符合的跳过
- return;
- int p = currentUrl.IndexOf(URL_FLAG, StringComparison.OrdinalIgnoreCase); //无参的也跳过
- if (p == -1) return;
- currentUrl = currentUrl.Substring(0, currentUrl.Length - URL_SUFFIX.Length); //去除后缀
- string url = string.Format("{0}.aspx", currentUrl.Substring(0, p));
- string query = FormmatUrlToQuery(currentUrl.Substring(p + URL_FLAG.Length));
- app.Context.RewritePath(url, string.Empty, query);
- }
- private string FormmatUrlToQuery(string url)
- {
- int j = 0; //计数器
- int len = url.Length;
- char[] chars = new char[len];
- for (int i = 0; i < len; i++)
- {
- if (url[i] != '/')
- chars[i] = url[i];
- else
- {
- if (++j % 2 == 1)
- chars[i] = '=';
- else
- chars[i] = '&';
- }
- }
- return new string(chars);
- }
- public void Dispose() { }
- }
复制代码 |