ASP编程 PHP编程 JSP编程 NET编程 CGI编程 XML编程 
Google adsense申请技巧本站核心代理域名注册主机业务 快速发布你的买卖域名买卖网站信息 1元注册 cn域名
站长每日新闻导读 √ ·推荐万网空间¥120元 150m 站长网:站长必上的网站网站联盟大全本站代理万网域名55空间120元
 2007-7-6 10:55:59

asp.net 2.0中的URL重写以及urlMappings问题

来源: 字体:[ ]

在asp.net2.0中的urlMappings倒是非常好用,可惜暂不支持正则表达式,不过,好在如果用IHttpModule的话 
  不管什么样的请求都会先经过IHttpModule这样就为URL重写提供了一个好机会: 
   
  下面是我写的一个IHttpModule: 
   
  using System; 
  using System.Web; 
   
  public class ReWriteModule:IHttpModule 
  { 

   public ReWriteModule() 

   { 
   } 

   public override string ToString() 
   { 
   return this.GetType().ToString(); 
   } 
  void IHttpModule.Dispose() 
  { 

  } 

   private static System.Xml.XmlDocument ruleDoc = null; 

   private static System.Xml.XmlDocument GetRuleConfig(System.Web.HttpContext app) 
   { 
   if (ruleDoc == null) 

   { 

   ruleDoc = new System.Xml.XmlDocument(); 
   ruleDoc.Load(app.Server.MapPath("~/rule.xml")); 
   } 

   return ruleDoc; 
   } 

   public static string GetUrl(System.Web.HttpContext cxt,string path) 
   { 

   System.Xml.XmlDocument doc = GetRuleConfig(cxt); 

   System.Xml.XmlNodeList lst= doc.GetElementsByTagName("RewriterRule"); 

   string pat=""; 
   foreach (System.Xml.XmlNode nd in lst) 
   { 
   System.Xml.XmlNodeList sub = nd.ChildNodes[0].ChildNodes; 

   foreach(System.Xml.XmlNode chk in sub) 

   { 
   pat = "^" + chk.InnerText+"$"; 
   System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(pat, System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase); 
   if(reg.IsMatch(path)) 

   { 
   return reg.Replace(path, nd.ChildNodes[1].InnerText); 

   } 
   } 
   } 

   return null; 
   
   } 
  void IHttpModule.Init(HttpApplication context) 

  { 

   context.BeginRequest += delegate(object sender, EventArgs e) 
   { 

   System.Web.HttpContext cxt = context.Context; 
      if (cxt.Request.ContentType != "image/pjpeg") 
   { 
   string type = cxt.Request.ContentType.ToLower(); 

   string path = cxt.Request.Path; 

   string apppath = cxt.Request.ApplicationPath; 
   path = path.Remove(0, apppath.Length); 
   path = "~" + path; 
   
   string newUrl = GetUrl(cxt, path.TrimEnd().TrimStart());
   if (newUrl != null) 
   { 
   cxt.Response.Filter = new ResponseFilter(cxt.Response.Filter,cxt.Request.Path); 
   cxt.Response.Write("请求的路径:" + path); 
   cxt.Response.Write("<BR>"); 
   cxt.Response.Write("转向的目的URL:" + newUrl); 
   cxt.Response.Write("<BR>"); 
   cxt.RewritePath(newUrl); 
   
   }//如果要求处理所有的请求时用到 
   //else 
   //{ 
   // cxt.Response.Write(cxt.Request.Path + "<BR>"); 
   // cxt.Response.Write("你请求的资源不存在或无权访问!"); 
   // cxt.Response.Flush(); 

   // cxt.Response.End(); 

   //} 

   } 

      }; 

  } 

    }                                    

网站地图 - 域名注册续费虚拟主机代理 - 交易论坛 - 网站投稿 - 广告服务 - 帮助中心 - 联系我们
Copyright ©2003-2007 www.Admin5.com All Rights Reserved