Cannot redirect after HTTP headers have been sent.

Friday, 2 September 2016

Cannot redirect after HTTP headers have been sent.

This is an unhanded exception shown may be shown due to the following reason 

1: some times we write code like this 
            .....
            ......
// Now that you have all the bytes representing the PDF report, buffer it and send it to the client.   
            Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename= filename" + "." +                         extension);
            Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
            Response.Flush(); // send it to the client to download  
            Response.End();

suppose after completing this i want to redirect to another page, so i have to write Response.Redirect("Home.aspx"); 
or suppose we write the above code like this 
           try
          {
              .................................................
                        Response.Buffer = true;
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename= filename" + "." +                         extension);
            Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
            Response.Flush(); // send it to the client to download  
            Response.End();
              ...
             ......
             .....
           }
          catch()
         {
            Response.Redirect("ErrorPage.aspx"); 
          }
suppose after executing Response.Flush(); code an exception occur the it will create second response, in both the cases you will get the same error.With HTTP you get one response for one request. Your browser requested the page only once,  
                    Response.Flush(); //First Response
                    Response.Redirect("mithunpatra.blogspot.com"); //Second Response


2: Suppose you have a button control and you want to generate a large report on clicking the button. To generate the report we have redirect it to another page. Now suppose user click on the button two times in a row that means it will generate  two request, In slow network before processing the fast request second request come but HTTP get only one request and one response that time you can get the above error. to solve this error you can use this code
              if (Response.IsRequestBeingRedirected =false)
                     {
                       response.redirrect("mithunpatra.blogspot.com");
                     }

with this code we can ensure one response for one request