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() 时?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01