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

通过引用UrlRewrite.dll,只需添加两行即可实现URL重写.

  1. public class MyHttpModule : IHttpModule
  2. {
  3.   public void Init(HttpApplication app)
  4.   {
  5.    app.AuthorizeRequest += new EventHandler(app_AuthorizeRequest);
  6.   }
  7.   public void Dispose() {}
  8.   protected void Rewrite(string requestedPath, System.Web.HttpApplication app)
  9.   {
  10.    //   app.Context.RewritePath("~/default.aspx", string.Empty, "test=tttttttt");
  11.    foreach(URLRewrite url in SiteUrls.GetSiteUrls().Urls)
  12.    {
  13.     if (Regex.IsMatch(app.Context.Request.Path, url.Pattern, RegexOptions.Compiled|RegexOptions.IgnoreCase))
  14.     {
  15.      app.Context.RewritePath(url.Page, string.Empty, Regex.Replace(app.Context.Request.Path, url.Pattern, url.QueryString, RegexOptions.Compiled|RegexOptions.IgnoreCase));
  16.      return;
  17.     }
  18.    }
  19.    if (app.Context.Request.Path.ToLower().EndsWith(".shtml"))
  20.    {
  21.     app.Context.Response.Redirect("~/index.html");
  22.    }
  23.   }
  24.   private void app_AuthorizeRequest(object sender, EventArgs e)
  25.   {
  26.    HttpApplication app = (HttpApplication) sender;
  27.    Rewrite(app.Request.Path, app);
  28.   }
  29.  }
  30.  public class SiteUrls
  31.  {
  32.   #region 内部属性和方法
  33.   string SiteUrlsFile = HttpContext.Current.Server.MapPath(ConfigurationSettings.AppSettings["SiteUrls"]);
  34.   private ArrayList _Urls;
  35.   public ArrayList Urls
  36.   {
  37.    get
  38.    {
  39.     return _Urls;
  40.    }
  41.    set
  42.    {
  43.     _Urls = value;
  44.    }
  45.   }
  46.   private NameValueCollection _Paths;
  47.   public NameValueCollection Paths
  48.   {
  49.    get
  50.    {
  51.     return _Paths;
  52.    }
  53.    set
  54.    {
  55.     _Paths = value;
  56.    }
  57.   }
  58.   
  59.   private SiteUrls()
  60.   {
  61.    string applicationPath = HttpContext.Current.Request.ApplicationPath;
  62.    if (applicationPath == "/")
  63.    {
  64.     applicationPath = string.Empty;
  65.    }
  66.    Urls = new ArrayList();
  67.    Paths = new NameValueCollection();
  68.    Paths.Add("home", applicationPath);
  69.    XmlDocument xml = new XmlDocument();
  70.    xml.Load(SiteUrlsFile);
  71.    XmlNode root = xml.SelectSingleNode("SiteUrls");
  72.    foreach(XmlNode n in root.ChildNodes)
  73.    {
  74.     if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "rewrite")
  75.     {
  76.      XmlAttribute name = n.Attributes["name"];
  77.      XmlAttribute path = n.Attributes["path"];
  78.      XmlAttribute page = n.Attributes["page"];
  79.      XmlAttribute querystring = n.Attributes["querystring"];
  80.      XmlAttribute pattern = n.Attributes["pattern"];
  81.      if (name != null && path != null && page != null && querystring != null && pattern != null)
  82.      {
  83.       Paths.Add(name.Value, applicationPath + path.Value);
  84.       Urls.Add(new URLRewrite(name.Value, Paths["home"]+pattern.Value, Paths["home"]+page.Value.Replace("^""&"), querystring.Value.Replace("^""&")));
  85.      }
  86.     }
  87.    }
  88.   }
  89.   #endregion
  90.   public static SiteUrls GetSiteUrls()
  91.   {
  92.    string CacheKey = "SiteUrls";
  93.    SiteUrls urls = System.Web.HttpContext.Current.Cache["SiteUrls"as SiteUrls;
  94.    if (urls == null)
  95.    {
  96.     urls = new SiteUrls();
  97.     System.Web.HttpContext.Current.Cache.Insert(CacheKey, urls, new CacheDependency(urls.SiteUrlsFile), DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.High, null);
  98.    }
  99.    return urls;
  100.   }
  101.   /// <summary>
  102.   /// 输出URL示例
  103.   /// </summary>
  104.   /// <param name="id"></param>
  105.   /// <returns></returns>
  106.   public string Show(int id)
  107.   {
  108.    return string.Format(Paths["Show"], id);
  109.   }
  110.  public class URLRewrite
  111.  {
  112.   #region 成员变量
  113.   private string _Name;
  114.   public string Name
  115.   {
  116.    get
  117.    {
  118.     return _Name;
  119.    }
  120.    set
  121.    {
  122.     _Name = value;
  123.    }
  124.   }
  125.   private string _Pattern;
  126.   public string Pattern
  127.   {
  128.    get
  129.    {
  130.     return _Pattern;
  131.    }
  132.    set
  133.    {
  134.     _Pattern = value;
  135.    }
  136.   }
  137.   private string _Page;
  138.   public string Page
  139.   {
  140.    get
  141.    {
  142.     return _Page;
  143.    }
  144.    set
  145.    {
  146.     _Page = value;
  147.    }
  148.   }
  149.   private string _QueryString;
  150.   public string QueryString
  151.   {
  152.    get
  153.    {
  154.     return _QueryString;
  155.    }
  156.    set
  157.    {
  158.     _QueryString = value;
  159.    }
  160.   }
  161.   #endregion 
  162.   #region 构造函数
  163.   public URLRewrite(string name, string pattern, string page, string querystring)
  164.   {
  165.    _Name = name;
  166.    _Pattern = pattern;
  167.    _Page = page;
  168.    _QueryString = querystring;
  169.   }
  170.   #endregion
  171.  }
  172.  public class PageBase : Page
  173.  {
  174.    <summary>
  175.   ///  重写默认的HtmlTextWriter方法,修改form标记中的value属性,使其值为重写的URL而不是真实URL。
  176.   /// </summary>
  177.   /// <param name="writer"></param>
  178.   protected override void Render(HtmlTextWriter writer)
  179.   {
  180.    if (writer is System.Web.UI.Html32TextWriter)
  181.    {
  182.     writer = new FormFixerHtml32TextWriter(writer.InnerWriter);
  183.    }
  184.    else
  185.    {
  186.     writer = new FormFixerHtmlTextWriter(writer.InnerWriter);
  187.    }
  188.    base.Render(writer);
  189.   }
  190.  }
  191.  internal class FormFixerHtml32TextWriter : System.Web.UI.Html32TextWriter
  192.  {
  193.   private string _url; // 假的URL
  194.   internal FormFixerHtml32TextWriter(TextWriter writer):base(writer)
  195.   {
  196.    _url = HttpContext.Current.Request.RawUrl;
  197.   }
  198.   public override void WriteAttribute(string name, string value, bool encode)
  199.   {
  200.    // 如果当前输出的属性为form标记的action属性,则将其值替换为重写后的虚假URL
  201.    if (_url != null && string.Compare(name, "action"true) == 0)
  202.    {
  203.     value = _url;
  204.    }
  205.    base.WriteAttribute(name, value, encode);
  206.   }
  207.  }
  208.      
  209.  internal class FormFixerHtmlTextWriter : System.Web.UI.HtmlTextWriter
  210.  {
  211.   private string _url;
  212.   internal FormFixerHtmlTextWriter(TextWriter writer):base(writer)
  213.   {
  214.    _url = HttpContext.Current.Request.RawUrl;
  215.   }
  216.   public override void WriteAttribute(string name, string value, bool encode)
  217.   {
  218.    if (_url != null && string.Compare(name, "action"true) == 0)
  219.    {
  220.     value = _url;
  221.    }
  222.    base.WriteAttribute(name, value, encode);
  223.   }
  224.  }

重写配置文件:

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <SiteUrls>
  3.  <!--如果重写shtml扩展名,需要在IIS里,调整应用程序映射,把shtml扩展名映射到C:/WINDOWS/Microsoft.NET/Framework/v1.1.4322/aspnet_isapi.dll,注意取消检查文件是否存在-->
  4.  <!--访问方式http://localhost/Example/Show/323.shtml-->
  5.     <rewrite name="Show"
  6.           path="/Show/{0}.shtml"
  7.           pattern = "/Show/(/d+).shtml"
  8.           page="/WebForm1.aspx"
  9.           querystring="id=$1^cn=ItemList" />
  10. </SiteUrls>

web.config里加入:

  1. <appSettings>
  2.   <add key="SiteUrls" value="~/SiteUrls.config"/>
  3.     </appSettings>
  4.  <httpModules>
  5.   <add name="MyHttpModule" type="UrlRewrite.MyHttpModule,UrlRewrite" />
  6.  </httpModules>

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值