首页 > 开发 > 综合 > 正文

实现快速简单高效并可以灵活配置的URL重写方案

2024-07-21 02:29:15
字体:
来源:转载
供稿:网友
,欢迎访问网页设计爱好者web开发。

需要源代码请在评论里留下email

关键代码: 
public class myhttpmodule : ihttpmodule
 {
  public void init(httpapplication app)
  {
   app.authorizerequest += new eventhandler(app_authorizerequest);
  }

  public void dispose() {}

  protected void rewrite(string requestedpath, system.web.httpapplication app)
  {
   //   app.context.rewritepath("~/default.aspx", string.empty, "test=tttttttt");
   foreach(urlrewrite url in siteurls.getsiteurls().urls)
   {
    if (regex.ismatch(app.context.request.path, url.pattern, regexoptions.compiled|regexoptions.ignorecase))
    {
     app.context.rewritepath(url.page, string.empty, regex.replace(app.context.request.path, url.pattern, url.querystring, regexoptions.compiled|regexoptions.ignorecase));
     return;
    }
   }
   if (app.context.request.path.tolower().endswith(".shtml"))
   {
    app.context.response.redirect("~/index.html");
   }
  }

  private void app_authorizerequest(object sender, eventargs e)
  {
   httpapplication app = (httpapplication) sender;
   rewrite(app.request.path, app);
  }
 }

 public class siteurls
 {
  #region 内部属性和方法
  string siteurlsfile = httpcontext.current.server.mappath(configurationsettings.appsettings["siteurls"]);
  private arraylist _urls;
  public arraylist urls
  {
   get
   {
    return _urls;
   }
   set
   {
    _urls = value;
   }
  }

  private namevaluecollection _paths;
  public namevaluecollection paths
  {
   get
   {
    return _paths;
   }
   set
   {
    _paths = value;
   }
  }
  
  private siteurls()
  {
   string applicationpath = httpcontext.current.request.applicationpath;

   if (applicationpath == "/")
   {
    applicationpath = string.empty;
   }

   urls = new arraylist();
   paths = new namevaluecollection();
   paths.add("home", applicationpath);

   xmldocument xml = new xmldocument();

   xml.load(siteurlsfile);

   xmlnode root = xml.selectsinglenode("siteurls");
   foreach(xmlnode n in root.childnodes)
   {
    if (n.nodetype != xmlnodetype.comment && n.name.tolower() == "rewrite")
    {
     xmlattribute name = n.attributes["name"];
     xmlattribute path = n.attributes["path"];
     xmlattribute page = n.attributes["page"];
     xmlattribute querystring = n.attributes["querystring"];
     xmlattribute pattern = n.attributes["pattern"];

     if (name != null && path != null && page != null && querystring != null && pattern != null)
     {
      paths.add(name.value, applicationpath + path.value);
      urls.add(new urlrewrite(name.value, paths["home"]+pattern.value, paths["home"]+page.value.replace("^", "&"), querystring.value.replace("^", "&")));
     }
    }
   }
  }
  #endregion

  public static siteurls getsiteurls()
  {
   string cachekey = "siteurls";
   siteurls urls = system.web.httpcontext.current.cache["siteurls"] as siteurls;
   if (urls == null)
   {
    urls = new siteurls();
    system.web.httpcontext.current.cache.insert(cachekey, urls, new cachedependency(urls.siteurlsfile), datetime.maxvalue, timespan.zero, cacheitempriority.high, null);
   }

   return urls;
  }

  /// <summary>
  /// 输出url示例
  /// </summary>
  /// <param name="id"></param>
  /// <returns></returns>
  public string show(int id)
  {
   return string.format(paths["show"], id);
  }

 public class urlrewrite
 {
  #region 成员变量
  private string _name;
  public string name
  {
   get
   {
    return _name;
   }
   set
   {
    _name = value;
   }
  }

  private string _pattern;
  public string pattern
  {
   get
   {
    return _pattern;
   }
   set
   {
    _pattern = value;
   }
  }

  private string _page;
  public string page
  {
   get
   {
    return _page;
   }
   set
   {
    _page = value;
   }
  }

  private string _querystring;
  public string querystring
  {
   get
   {
    return _querystring;
   }
   set
   {
    _querystring = value;
   }
  }
  #endregion

  #region 构造函数
  public urlrewrite(string name, string pattern, string page, string querystring)
  {
   _name = name;
   _pattern = pattern;
   _page = page;
   _querystring = querystring;
  }
  #endregion
 }

 public class pagebase : page
 {
  private pagebase()
  {
   //
   // todo: 在此处添加构造函数逻辑
   //
  }

  //// <summary>
  ///  重写默认的htmltextwriter方法,修改form标记中的value属性,使其值为重写的url而不是真实url。
  /// </summary>
  /// <param name="writer"></param>
  protected override void render(htmltextwriter writer)
  {

   if (writer is system.web.ui.html32textwriter)
   {
    writer = new formfixerhtml32textwriter(writer.innerwriter);
   }
   else
   {
    writer = new formfixerhtmltextwriter(writer.innerwriter);
   }

   base.render(writer);
  }
 }

 internal class formfixerhtml32textwriter : system.web.ui.html32textwriter
 {
  private string _url; // 假的url

  internal formfixerhtml32textwriter(textwriter writer):base(writer)
  {
   _url = httpcontext.current.request.rawurl;
  }

  public override void writeattribute(string name, string value, bool encode)
  {
   // 如果当前输出的属性为form标记的action属性,则将其值替换为重写后的虚假url
   if (_url != null && string.compare(name, "action", true) == 0)
   {
    value = _url;
   }
   base.writeattribute(name, value, encode);
  }
 }

    
 internal class formfixerhtmltextwriter : system.web.ui.htmltextwriter
 {
  private string _url;
  internal formfixerhtmltextwriter(textwriter writer):base(writer)
  {
   _url = httpcontext.current.request.rawurl;
  }

  public override void writeattribute(string name, string value, bool encode)
  {
   if (_url != null && string.compare(name, "action", true) == 0)
   {
    value = _url;
   }

   base.writeattribute(name, value, encode);
  }
 }

重写配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<siteurls>
 <!--如果重写shtml扩展名,需要在iis里,调整应用程序映射,把shtml扩展名映射到c:/windows/microsoft.net/framework/v1.1.4322/aspnet_isapi.dll,注意取消检查文件是否存在-->
 <!--访问方式http://localhost/example/show/323.shtml-->
    <rewrite name="show"
          path="/show/{0}.shtml"
          pattern = "/show/(/d+).shtml"
          page="/webform1.aspx"
          querystring="id=$1^cn=itemlist" />

</siteurls>

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表