木子屋 Dnawo's BLOG

推荐使用Redirect(string url, bool endResponse)进行客户端重定向

👤 dnawo 📅 2008-06-30 👁 6697 👍 0 💬 0 🔄 来源:本站原创
当我们使用Response.Redirect("Default2.aspx")来进行客户端重定向时,是无条件的、立即进行重定向,这在ASP时代可能引发一些问题,比如在重定向前打开的数据库连接如果没在重定向时及时关闭的话就会导致服务器资源被大量占用,所以每次使用Response.Redirect时我们都得时刻记得去关闭释放那些资源,这个问题在ASP.NET2.0中已经得到了解决,在ASP.NET2.0中Response.Redirect有两个重载函数:

public void Redirect(string url);
public void Redirect(string url, bool endResponse);


重载函数Redirect(string url, bool endResponse)的参数endResponse表示当前页的执行是否应终止,true 终止,false不终止,这样我们就可以使用Response.Redirect("Default2.aspx",false)来解决上述的问题:程序仍按原来的流程在不需要连接时关闭释放数据库连接即可,不用在Redirect前多加一步去关闭释放!下边再举个例子说明:

Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["test"] = "hello world!";
        Response.Redirect("Default2.aspx",true);
        Session.Contents.Remove("test");
    }

}

Default2.aspx.cs:
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Session["test"] + "");
    }
}

结果:Default2.aspx上显示"hello world!",此时和使用Response.Redirect("Default2.aspx")是一样的。

Default.aspx.cs:
public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        Session["test"] = "hello world!";
        Response.Redirect("Default2.aspx",false);
        Session.Contents.Remove("test");
    }

}

Default2.aspx.cs:
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write(Session["test"] + "");
    }
}

结果:Default2.aspx不显示内容。

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 使用类设计器设计类 下一篇 → ASP.NET2.0个性化用户配置之SQL Server数据库配…