为什么我会和QUOT;经过HTTP标头已被送往&QUOT不能重定向;当我打电话的Response.Redirect()? [英] Why do I get "Cannot redirect after HTTP headers have been sent" when I call Response.Redirect()?

查看:229
本文介绍了为什么我会和QUOT;经过HTTP标头已被送往&QUOT不能重定向;当我打电话的Response.Redirect()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我称之为的Response.Redirect(someUrl)我得到一个HttpException:无法重定向后,HTTP标头已发送

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?

推荐答案

根据MSDN文档的Response.Redirect(字符串URL),它会抛出一个HttpException时HTTP头已经发出后重定向尝试。由于的Response.Redirect(字符串URL)使用HTTP位置响应头(<一个href=\"http://en.wikipedia.org/wiki/HTTP_headers#Responses\">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 属性(布尔)的一种方式。

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");

这篇关于为什么我会和QUOT;经过HTTP标头已被送往&QUOT不能重定向;当我打电话的Response.Redirect()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆