目标:将网页地址伪静态
实现:在Global.asax中改写:
protected void Application_BeginRequest(object sender, EventArgs e)
{
string pattern = @"(MagazineContent)(\d+)(.aspx)";
MyRewritePatht(pattern);//将MagazineContentAjax.aspx?id=n改写为MagazineContentn.aspx的形式(n为参数,注意调用的方法为MyRewritePatht,与下面的不同)
string pattern1 = @"(Dynamiccontend)(\d+)(.aspx)";
MyRewritePath(pattern1);//将Dynamiccontend.aspx?id=n改写为Dynamiccontendn.aspx的形式
string pattern2 = @"(MagazineCategoryList)(\d+)(.aspx)";
MyRewritePath(pattern2);//将Dynamiccontend.aspx?id=n改写为Dynamiccontendn.aspx的形式
string pattern3 = @"(MagazineCategoryList1)(\d+)(.aspx)";
MyRewritePath(pattern3); //将MagazineCategoryList1.aspx?id=n改写为MagazineCategoryList1n.aspx的形式
string pattern4 = @"(MagazineCategoryList2)(\d+)(.aspx)";
MyRewritePath(pattern4);//将MagazineCategoryList2.aspx?id=n改写为MagazineCategoryList2n.aspx的形式
}
protected void MyRewritePath(string pattern)
{
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, "$1$3?id=$2", RegexOptions.Compiled | RegexOptions.IgnoreCase);
this.Context.RewritePath(newUrl);
}
}
protected void MyRewritePatht(string pattern)
{
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, "$1Ajax$3?id=$2", RegexOptions.Compiled | RegexOptions.IgnoreCase);
this.Context.RewritePath(newUrl);
}
}
前台页面:
将原有的代码做相应的修改(注意参数位置的变化),如:
<a href='MagazineContent.aspx?id=<%# Eval("id") %>' target="_blank">详细...</a>
改为:<a href='MagazineContent<%# Eval("id") %>.aspx' target="_blank">详细...</a>