当我调用 Response.Redirect(someUrl)
我得到以下 HttpException:
When I call Response.Redirect(someUrl)
I get the following HttpException:
发送 HTTP 标头后无法重定向.
Cannot redirect after HTTP headers have been sent.
为什么我会得到这个?我该如何解决这个问题?
Why do I get this? And how can I fix this issue?
根据Response.Redirect(string url)
的MSDN文档,当尝试重定向之后会抛出HttpExceptionHTTP 标头已发送".由于 Response.Redirect(string url)
使用 Http "Location" 响应标头 (http://en.wikipedia.org/wiki/HTTP_headers#Responses),调用它将导致标头发送到客户端.这意味着如果您第二次调用它,或者如果您在以其他方式发送标头后调用它,您将获得 HttpException.
According to the MSDN documentation for Response.Redirect(string url)
, it will throw an HttpException when "a redirection is attempted after the HTTP headers have been sent". Since Response.Redirect(string url)
uses the Http "Location" response header (http://en.wikipedia.org/wiki/HTTP_headers#Responses), calling it will cause the headers to be sent to the client. This means that if you call it a second time, or if you call it after you've caused the headers to be sent in some other way, you'll get the HttpException.
防止多次调用 Response.Redirect() 的一种方法是在调用之前检查 Response.IsRequestBeingRedirected
属性 (bool).
One way to guard against calling Response.Redirect() multiple times is to check the Response.IsRequestBeingRedirected
property (bool) before calling it.
// Causes headers to be sent to the client (Http "Location" response header)
Response.Redirect("http://www.stackoverflow.com");
if (!Response.IsRequestBeingRedirected)
// Will not be called
Response.Redirect("http://www.google.com");
这篇关于为什么我会收到“发送 HTTP 标头后无法重定向"?当我调用 Response.Redirect() 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!