首页 > 代码库 > 重定向实例

重定向实例

1.Server.Transfer

        //内部重定向到静态资源
        protected void Button1_Click(object sender, EventArgs e)
        {
            Server.Transfer("~/img/1.jpg");
            Response.Write("此后的代码不会执行");

            string filename = LocalPathHelper.DesktopPath + "/text.txt";
            FileStream stream = File.Create(filename);
            stream.Close();
        }

        //内部重定向到动态页面
        protected void Button2_Click(object sender, EventArgs e)
        {
            //追加参数,url方式
            Server.Transfer("~/view/LoginTwo.aspx?username=admin");


            //追加headers
            NameValueCollection coll = new NameValueCollection();
            coll.Add("adf", "1234");
            Server.TransferRequest("~/view/LoginTwo.aspx", true, "POST", coll);


            //不能请求外域
            //Server.Transfer("http://www.baidu.com");
        }

2.Response.Redirect

        //请求外域
        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Redirect("http://www.baidu.com");
        }

        //带参数传递
        protected void Button2_Click(object sender, EventArgs e)
        {
            //url方式指定参数
            Response.Redirect("~/view/LoginTwo.aspx?username=admin");

            //永久重定向
            Response.RedirectPermanent("~/view/LoginTwo.aspx?username=admin");
        }

        //请求静态资源
        protected void Button3_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/img/1.jpg");
        }