Response.Redirect()在Response.Flush()之后;

时间:2018-05-14 13:01:57

标签: c# asp.net

在我的代码中,我想在下载pdf后重定向到thankyou.html页面,以便我在该方法中创建download()我编写代码

protected void download()
    {
        try
        {
            string path = Server.MapPath("pdf/myDoc.pdf");   
            System.IO.FileInfo file = new System.IO.FileInfo(path);
            if (file.Exists)
            {
                string strURL = path;
                WebClient req = new WebClient();

                Response.Clear();
                Response.ClearContent();
                Response.ClearHeaders();
                Response.Buffer = true;
                Response.AddHeader("Content-Disposition", "attachment;filename=\"myDoc.pdf\"");
                byte[] data = req.DownloadData(path);
                Response.BinaryWrite(data);
                Response.Flush();

                Response.Redirect("thankyou.html");
            }                
            else
            {
                Response.Write("This file does not exist.");
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('" + ex.Message.ToString() + "');", true);
        }
    }

但它显示错误无法评估表达式,因为代码已优化或本机框架位于调用堆栈顶部以及Response.Redirect(" thankyou.html&#34) );在外面显示错误在发送HTTP标头后无法重定向。 你能指导我如何重定向到另一个页面吗?

1 个答案:

答案 0 :(得分:8)

你做不到。发送文件并重定向到页面是两个单独的HTTP响应。你无法将它们结合起来。

经常做的是,下载是由您返回的页面触发的,因此当您显示谢谢消息时,有一些javascript负责下载。如果您愿意,可以使用此javascript:Download File Using Javascript/jQuery