通过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中做配置。
 
        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));
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值