zoukankan      html  css  js  c++  java
  • asp.net 2.0 简单实现url重写

    今天,群里有人问我关于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.轻松的几行代码搞定!

    版权声明:本文原创发表于 博客园,作者为 路过秋天 本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则视为侵权。
    个人微信公众号
    创业QQ群:617713515
    Donation(扫码支持作者):支付宝:
    Donation(扫码支持作者):微信:
  • 相关阅读:
    python切片操作
    python中的内存管理
    python中x,y交换值的问题
    leetcode6:Zigzag Conversion@Python
    Leetcode4:Median of Two Sorted Arrays@Python
    Leetcode3:Longest Substring Without Repeating Characters@Python
    Leetcode2:Add Two Numbers@Python
    LeetCode344:Reverse String@Python
    支付宝 芝麻信用分过600,你不知道的八个特权
    穷爸爸富爸爸里面说的“现金流游戏”靠谱吗?
  • 原文地址:https://www.cnblogs.com/cyq1162/p/574548.html
Copyright © 2011-2022 走看看