Unable to redirect after sending HTTP headers
When I try to redirect to another page via Response.Redirect(URL)
I get the following error: -System.Web.HttpException: Cannot redirect after HTTP headers have been sent.
I wrote one Response.Write("Sometext")
; and Response.Flush()
before calling the redirect method.
In this case, how do we use Response.Redirect(URL)
?
I am executing a stored procedure through an Asynch call. It takes almost 3 minutes to complete the SP. By then I will get server load balancing timeout error because this application is running on the Cloud machine. To avoid time-out load balancing, I write the text in the browser ( response.write()
and Flush()
).
a source to share
You need to make sure you don't write or flush anything before trying to send the HTTP header. After the headers are sent, there is no right way to do the redirect as the only thing you can do is output JavaScript to redirect (bad) or send a meta refresh / location tag that most likely is not in the correct position (inside the HEAD) and hence result in invalid html.
a source to share
I had the same error and same approach. You might want to try using javascript instead of calling Response.Redirect directly.
Response.Write("<script type='text/javascript'>");
Response.Write("window.location = '" + url + "'</script>");
Response.Flush();
Worked well with me, but I still need to test it on different browsers.
a source to share
You cannot use Response.Redirect because you went past the headers and wrote out "Sometext". You must check (redirect condition) before you start writing data to client or redirecting META.
If you want one of these pages to display text and redirects after 5 seconds, you can select META.
a source to share
You won't get this error if you redirect to the start of your page (for example, when you redirect events Load
or PreRender
on a page).
Now I can see in your comments that you want to redirect after the lengthy stored procedure has finished. You may need to take a different approach in this case.
You can put, for example, AJAX UpdatePanel
s Timer
on your page, and a Timer can check every few seconds if the stored procedure has finished and then redirect.
This approach also has the advantage that you can put some on-the-fly message on the page while the procedure is in progress, so your user will know what is still going on.
a source to share
In my case, the cause of the problem is that it takes a long time to load the data in the scroll view grid. And before the gridview data is fully loaded, but I will click the redirect button. I am getting this error.
You can shrink your data.
or
until the download is complete, you cannot press the redirect button
a source to share