asp.net2.0 URL重写以及urlMappings问题(1)

分类: asp.net技巧   出处:iocblog整理  更新时间:2008-12-30   添加到收藏  

  在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("
");
   cxt.response.write("转向的目的url:" + newurl);
   cxt.response.write("
");
   cxt.rewritepath(newurl);
  
  
  
   }//如果要求处理所有的请求时用到
   //else
   //{ [来源www.iocblog.net]
   // cxt.response.write(cxt.request.path + "
");
   // cxt.response.write("你请求的资源不存在或无权访问!");
   // cxt.response.flush();
   // cxt.response.end();
   //}
   }
  
   };
   }
  
  
  }
 [来源www.iocblog.net]


Tag: URL重写



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。