0

In my code, I want to redirect to a thankyou.html page after download pdf so that I crate download() in that method i write code

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);
        }
    }

But It shows me Error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack and when Response.Redirect("thankyou.html"); take outside it show me error Cannot redirect after HTTP headers have been sent. Can you guide me how to redirect to another page?

Tushar
  • 182
  • 3
  • 19
  • 2
    You can only send one response, not two. Either a file *or* a redirect. It sounds like you need to re-think the sequence of steps in the user experience a bit. Perhaps direct the user to a "thank you" page which itself contains a link to download the file? – David May 14 '18 at 13:04
  • @PatrickHofman the answer didn't appear on my computer when I sent my comment. I'll delete it. – the_lotus May 14 '18 at 13:12

1 Answers1

8

You can't. Sending a file and redirecting to a page are two separate HTTP responses. You can't combine them.

What is done quite often, is that the download is triggered by the page you return, so there is some javascript taking care of the download while you display a thank you message. If you want to, you can use this javascript: Download File Using Javascript/jQuery.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325