且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

asp.net 2.0 简单实现url重写

更新时间:2022-10-02 13:57:38

今天,群里有人问我关于Url重写的问题,想这重写,记得国庆期间看过相关文章,msdn介绍也看过,大概就三种方法,最常用的就是用微软提供的dll文件,今天,把我dll引用了一下,按着说明配置了一下文件,结果出现不少问题,调试时找不到.cs源代码,不知是啥问题,可能dll放的太久,生秀了..-_-.#,只好上网再搜一下新的dll,突然发现2.0里的新方法!花了半个晚上做一个demo!
以下是demo源代码: 项目里只有两个页面(Default.aspx,user.aspx(直接response.write(request.querystring["userId"]))
protected void Application_BeginRequest(object sender, EventArgs e)

{
    string suffixUrl, lastUrl, newurl = string.Empty, userId = string.Empty ;
    lastUrl = Request.RawUrl;
    if (lastUrl.Substring(0, 11).ToLower() == "/urlrewrite")//"urlrewirte是根目录名,加判断的原因是本地测试时
     {                                                                //被取出来,上传到服务器时根目录会被域名取代(消失)!
        suffixUrl = lastUrl.Substring(12).ToLower();
    }
    else
    {
        suffixUrl = lastUrl.Substring(1).ToLower(); 
    }
    bool isMatch = false;
    Regex myReg = new Regex(@"user/([\w\d]+)\.aspx");
    if (myReg.IsMatch(suffixUrl))
    {
        isMatch = true;
        int first=suffixUrl.LastIndexOf('/')+1;
        int end=suffixUrl.LastIndexOf('.');
        int lenght=end-first;
        userId=suffixUrl.Substring(first,lenght);//获取被匹配的组部分
    }
    if (isMatch)
    {
       newurl="~/user.aspx?userId="+userId;
     }
    else
      {
        newurl = "~/Default.aspx";
       }

    HttpContext.Current.RewritePath(newurl); //最关键的一句话,重写Url
}

测试输入:http://xxx/urlrewrite/usre/cyq1162.aspx(地址栏显示)
成功定向到:http://xxx/urlrewrite/user.aspx?userid=cyq1162(页面内容显示)
..很简单吧..不用引入dll,也不用配置Webconfig.轻松的几行代码搞定!

版权声明:本文原创发表于博客园,作者为路过秋天,原文链接:http://www.cnblogs.com/cyq1162/archive/2006/11/28/574548.html