通过Global.asax实现简单的url重写
实现目标
在列表页list.aspx中点击某一条内容后显示该条内容的详细信息,一般通过details.aspx?id=5的方式实现,在url栏通过get方法提交参数,为做到对搜索引擎友好,url地址简单可对其进行重写,如list_5.aspx、或list/5.aspx等达到这样的效果。
编码实现,通过正则表达式匹配查找id,再重写
void Application_BeginRequest(object sender, EventArgs e)
{
string id = null;
Regex rg = new Regex(@"^.+list_\d+.aspx$");
string fullOrigionalpath = Request.Url.ToString();
if (rg.IsMatch(fullOrigionalpath))
{
MatchCollection regs = Regex.Matches(fullOrigionalpath, "list_(?<id>.+?).aspx", RegexOptions.IgnoreCase);
if (regs.Count > 0)
{
id = regs[0].Groups["id"].ToString();
}
Context.RewritePath("/website/details.aspx?id="+id);
}
}
通过页面链接<a href="list_5.aspx" title="">url rewrite</a>,url显示为list_5.aspx,而在details.aspx页面可接受到传递的参数Request.QueryString["id"]。
可以对Application_BeginRequest中的方法做适当的封装,对url参数在web.config中做配置。
在列表页list.aspx中点击某一条内容后显示该条内容的详细信息,一般通过details.aspx?id=5的方式实现,在url栏通过get方法提交参数,为做到对搜索引擎友好,url地址简单可对其进行重写,如list_5.aspx、或list/5.aspx等达到这样的效果。
编码实现,通过正则表达式匹配查找id,再重写
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
通过页面链接<a href="list_5.aspx" title="">url rewrite</a>,url显示为list_5.aspx,而在details.aspx页面可接受到传递的参数Request.QueryString["id"]。
可以对Application_BeginRequest中的方法做适当的封装,对url参数在web.config中做配置。
if (Regex.IsMatch(Request.Path, @"list_(\d+).aspx", RegexOptions.None | RegexOptions.IgnoreCase))
{
Context.RewritePath("details.aspx", string.Empty, Regex.Replace(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1), @"list_(\d+).aspx", "id=$1", RegexOptions.None | RegexOptions.IgnoreCase));
}
{
Context.RewritePath("details.aspx", string.Empty, Regex.Replace(Request.Path.Substring(Request.Path.LastIndexOf("/") + 1), @"list_(\d+).aspx", "id=$1", RegexOptions.None | RegexOptions.IgnoreCase));
}