日期:2014-05-16  浏览次数:20822 次

再谈<<在ASP.NET中重写URL>>
将之前的<<在ASP.NET中重写URL>>中的代码重构一下:
Global.asax.cs文体中:
protected void Application_BeginRequest(object sender, EventArgs e)
{
  string pattern = @"(ArticleContent)-(\d+).html";
  MyRewritePath(pattern, "$1.aspx?id=$2");
  //将ArticleContent.aspx?id=n改写为ArticleContent-n.html的形式(n为参数) 
  string pattern1 = @"(ArticleList)-(\d+).html";
  MyRewritePath(pattern1, "$1.aspx?caid=$2");
  //将ArticleList.aspx?caid=n改写为ArticleList-n.html的形式
  string pattern2 = @"(SsStorieDetailed)-(\d+).html";
  MyRewritePath(pattern2, "$1.aspx?id=$2");
  //将SsStorieDetailed.aspx?id=n改写为SsStorieDetailed-n.html的形式
}
protected void MyRewritePath(string pattern,string regex)
{
  string oldUrl = HttpContext.Current.Request.RawUrl;
  Match m = Regex.Match(oldUrl, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
  if (m.Success)
  {
    string newUrl = Regex.Replace(oldUrl, pattern, regex, RegexOptions.Compiled | RegexOptions.IgnoreCase);
    this.Context.RewritePath(newUrl);
  }
}