URL重寫

来源:互联网 发布:java创建内部类 编辑:程序博客网 时间:2024/05/20 05:28
 

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]

原创粉丝点击