ASP.NET 实现 URL 重写的方法

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

        /// <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 @ 2012-09-06 14:39  Charles Zhang  阅读(5034)  评论(1编辑  收藏  举报