Why do I get “Cannot redirect after HTTP headers h

2019-01-03 02:21发布

When I call Response.Redirect(someUrl) I get an HttpException: "Cannot redirect after HTTP headers have been sent".

Why do I get this? And how can I fix this issue?

15条回答
不美不萌又怎样
2楼-- · 2019-01-03 02:48

There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.

Just check your code for posible output or you can put the header on top of your method so it will be send first.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-03 02:48

I solved the problem using: Response.RedirectToRoute("CultureEnabled", RouteData.Values); instead of Response.Redirect.

查看更多
Rolldiameter
4楼-- · 2019-01-03 02:49

If you get Cannot redirect after HTTP headers have been sent then try this below code.

HttpContext.Current.Server.ClearError();
// Response.Headers.Clear();
HttpContext.Current.Response.Redirect("/Home/Login",false);
查看更多
别忘想泡老子
5楼-- · 2019-01-03 02:51

Just check if you have set the buffering option to false (by default its true). For response.redirect to work,

  1. Buffering should be true,
  2. you should not have sent more data using response.write which exceeds the default buffer size (in which case it will flush itself causing the headers to be sent) therefore disallowing you to redirect.
查看更多
SAY GOODBYE
6楼-- · 2019-01-03 02:57

If you are trying to redirect after the headers have been sent (if, for instance, you are doing an error redirect from a partially-generated page), you can send some client Javascript (location.replace or location.href, etc.) to redirect to whatever URL you want. Of course, that depends on what HTML has already been sent down.

查看更多
你好瞎i
7楼-- · 2019-01-03 02:58

My Issue got resolved by adding the Exception Handler to handle "Cannot redirect after HTTP headers have been sent". this Error as shown below code

catch (System.Threading.ThreadAbortException)
        {
            // To Handle HTTP Exception "Cannot redirect after HTTP headers have been sent".
        }
        catch (Exception e)
        {//Here you can put your context.response.redirect("page.aspx");}
查看更多
登录 后发表回答