Why do I get quot;Cannot redirect after HTTP headers have been sentquot; when I call Response.Redirect()?(为什么我会收到“发送 HTTP 标头后无法重定向?当我调用 Response.Redirect() 时?)
问题描述
当我调用 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() 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我会收到“发送 HTTP 标头后无法重定向"?当我调用 Response.Redirect() 时?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01