URL重寫

本文介绍了一个具体的URL重写实现案例,通过在Global.asax文件中添加Application_BeginRequest事件,实现了不同URL格式之间的转换。该方法使得网站能够使用更加友好且符合SEO规范的URL结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

url重寫,要把代碼寫在global文件中,默認的global文件中沒有給Application_BeginRequest事件,所以手工添加了一個

Application_BeginRequest 在程式被訪問時調用,發生在頁面初始化之前,故才可以使RewritePath生效

運用了該方法之后,訪問網頁時,url會是:

首頁:http://localhost/mypro/memberzone/suyangxian/index.aspx


http://localhost/mypro/memberzone/?uid=suyangxian

共享模塊:http://localhost/mypro/memberzone/suyangxian/share.aspx

http://localhost/mypro/memberzone/share.aspx?uid=suyangxian

[C# code]

void Application_BeginRequest(object sender, EventArgs e)
    {
        /*
         * 老地址,轉化成新地址
         * */
       
        HttpContext context = ((HttpApplication)sender).Context;
        string path = context.Request.Url.ToString().ToLower();
        if (path.Contains("memberzone/index.aspx?uid="))
        {           
            string questUid = Request.QueryString["uid"];
            if (!CoolFuncs.IsNullorEmpty(questUid))
            {
                //實際地址換成重寫之后的地址
                string ss = "index.aspx?uid=" + questUid;
                string rePath = path.Replace(ss, "");
                rePath += questUid + "/index.aspx";
                Response.Redirect(rePath);               
            }
        }else
       
        if (path.Contains("memberzone") && !path.Contains("uid"))
        {
            //分析地址
            string[] ps = path.Split('/');
            try
            {   
                //uid所在的index,這里要根據具體的域名作修改 ,
                //http://localhost/mypro/memberzone/suyangxian/index.aspx
                int k = 5;
                //獲得uid
                string uid = ps[k];
                if (uid != "")
                {
                    string new_path = path.Replace("/" + uid, "");
                    int l2 = new_path.Split('.').Length;

                    int l = new_path.Split('?').Length;
                    string op = (l > 1 ? "&" : "?");
                    string sURL = Pars.SiteUrl;
                   
                    //轉換成實際的地址
                    new_path += op + "uid=" + uid;

                    //必須要換成虛擬目錄的url
                    new_path = new_path.Replace(sURL, "~");

                    //重寫地址
                    context.RewritePath(new_path);

                }
            }
            catch (Exception Err)
            {
                string tErrors = Err.Message;
            }
        }
       
    }

[/C# code]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值