如何:将用户重定向到另一页

更新:2007 年 11 月

您可能希望将用户从一个 ASP.NET 网页重定向到另一个网页。例如,可能会在多页窗体中执行此操作。

重定向页的方法很多,比如以下方法:

  • 通过将页配置为发送到另一页 在此方案中,用户单击已配置的按钮可以发送到其他页。此方案多用于多页窗体。但需要用户交互。有关详细信息,请参见 ASP.NET 网页中的跨页发送

  • 通过动态使用浏览器 在此方案中,向用户的浏览器发送命令,使浏览器检索其他页。采用这种方法,能以编程方式重定向到另一页。但是,这种重定向会导致新的请求 (HTTP GET),并且从源页发送的所有数据都将丢失。

通过动态使用服务器端方法 在此方案中,服务器只向另一页传递上下文即可。其优点是您可以共享页之间的页上下文信息。其缺点是用户的浏览器不知道在进行传输,因此不更新浏览器的历史记录。如果用户刷新此页,则可能会产生意外的结果。有关在服务器传输期间共享页上下文的详细信息,请参见如何:在 ASP.NET 网页之间传递值

使用浏览器将用户重定向到另一页

  1. 将 Response 对象的 BufferOutput 属性设置为 true。

  2. 调用 Response 对象的 Redirect 方法,以向其传递用户重定向目标页的 URL。

    下面的代码示例演示如何根据局部变量 UserLanguage(在其他地方设置)的内容来进行页重定向。

    Response.BufferOutput = True
    If UserLanguage = "English" Then
        Response.Redirect("https://www.microsoft.com/gohere/look.htm")
    ElseIf UserLanguage = "Deutsch" Then
        Response.Redirect("https://www.microsoft.com/gohere/look_deu.htm")
    ElseIf UserLanguage = "Español" Then
        Response.Redirect("https://www.microsoft.com/gohere/look_esp.htm")
    End If
    
    Response.BufferOutput = true;
    if (UserLanguage == "English")
    {
        Response.Redirect("https://www.microsoft.com/gohere/look.htm");
    }
    else if (UserLanguage == "Deutsch")
    {
        Response.Redirect("https://www.microsoft.com/gohere/look_deu.htm");
    }
    else if (UserLanguage == "Español")
    {
        Response.Redirect("https://www.microsoft.com/gohere/look_esp.htm");
    }
    

使用服务器端方法将用户重定向到另一页

  • 调用 Transfer 方法,以向其传递用户重定向目标页的名称。

    下面的代码示例演示如何重定向到另一页。

    Protected Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
            Server.Transfer("Page2.aspx", True)
    End Sub
    
    protected void Button1_Click(object sender, System.EventArgs e)
    {
       Server.Transfer("Page2.aspx", true);
    }
    

请参见

任务

如何:在 ASP.NET 网页之间传递值