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() { } }