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() 时?
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- 从 C# 控制相机设备 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
