现在的位置: 首页 > 综合 > 正文

RewritePath() 实现简单高效的URL重写代码

2013年03月21日 ⁄ 综合 ⁄ 共 598字 ⁄ 字号 评论关闭
//原始的URL:http://www.ccol.cn/news/12/66.aspx
//转换后URL:http://www.ccol.cn/news.aspx?q1=12&q2=66

protected void Application_BeginRequest(Object sender, EventArgs e)
{
Regex re = new Regex(@"^((/[^/0-9]+)+)(/[0-9]+(/[^/]+)*)/.aspx$", RegexOptions.Compiled);
Match match = re.Match(HttpContext.Current.Request.Path);

if(match.Success)
{
re = new Regex(@"/([^/]+)", RegexOptions.Compiled);
MatchCollection matches = re.Matches(match.Result("$3"));

string page = match.Result("$1")+".aspx?q0="+matches[0].Result("$1");
for(int i=1; i<matches.Count; i++)
{
page += "&q"+i+"="+matches[i].Result("$1");
}

HttpContext.Current.RewritePath(page); //关键步骤
}
}

抱歉!评论已关闭.