using System;using System.IO;using System.Threading;using System.Web;using Com.Website.Configuration;using Com.Website.WebModel.Resource;using Com.Website.DomainModel;namespace Com.Website.HttpModule.UrlRewriter{ ////// Url rewrite http module /// public class UrlRewriteHttpModule : IHttpModule { private UrlHelper urlHelper; private RewriteRuleCollection rewriteRuleList = new RewriteRuleCollection(); public UrlRewriteHttpModule() { this.urlHelper = new UrlHelper(); } #region IHttpModule Members public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(OnBeginRequest); } public void Dispose() { } #endregion private void InitialSetting() { rewriteRuleList.Clear(); foreach (RewriteSetting rewriteSetting in ConfigurationManager.UrlRewriterConfiguration.RewriteConfiguration.RewriteSettingCollection) { RewriteRule rewrite = null; string providerName = rewriteSetting.Provider; if (string.IsNullOrEmpty(providerName)) { rewrite = UrlRewrite.CreateRewriteRule(); } else { rewrite = UrlRewrite.CreateRewriteRule(providerName); } rewrite.Initialize(rewriteSetting); rewriteRuleList.Add(rewrite); } } private void OnBeginRequest(object sender, EventArgs e) { HttpApplication application = sender as HttpApplication; if (File.Exists(application.Request.PhysicalPath)) return; if (!(ConfigurationManager.BizConfiguration != null && ConfigurationManager.UrlRewriterConfiguration != null && ConfigurationManager.UrlRewriterConfiguration.RewriteConfiguration != null && ConfigurationManager.UrlRewriterConfiguration.RewriteConfiguration.RewriteSettingCollection != null)) return; string pageName = string.Empty; if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Request.Url != null) { pageName = HttpContext.Current.Request.Url.AbsolutePath; } PageUrlAlias currentAlias = PageUrlAlias.InvalidUrl; if (!string.IsNullOrWhiteSpace(pageName)) { currentAlias = ConfigurationManager.WebPageConfiguration.GetPageUrlAlias(pageName); } if (ConfigurationManager.UrlRewriterConfiguration.ExceptPage != null && ConfigurationManager.UrlRewriterConfiguration.ExceptPage.Pages != null && ConfigurationManager.UrlRewriterConfiguration.ExceptPage.Pages.Exists(d => d == currentAlias)) { return; } InitialSetting(); string requestUrl = application.Request.RawUrl; string requestQuerystring = string.Empty; string virtualUrl = requestUrl; int pos = requestUrl.IndexOf('?'); if (pos >= 0) { requestQuerystring = requestUrl.Substring(pos + 1); virtualUrl = requestUrl.Substring(0, pos); } virtualUrl = virtualUrl.TrimEnd('/'); RewriteRule rewriteRule = rewriteRuleList.Find(new Predicate(delegate(RewriteRule rule) { return rule.IsRewrite(virtualUrl); })); if (rewriteRule == null) return; string destinationUrl = rewriteRule.RewriteUrl(virtualUrl); destinationUrl = urlHelper.JoinUrlParameter(urlHelper.HandleRootOperator(destinationUrl), requestQuerystring); HttpContext.Current.RewritePath(destinationUrl); } }}