为什么我会收到“发送 HTTP 标头后无法重定向"?当我调用 Response.Redirect() 时?

4

本文介绍了为什么我会收到“发送 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() 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Func<string,string> 有什么区别?和委托?
What is the difference between Funclt;string,stringgt; and delegate?(Funclt;string,stringgt; 有什么区别?和委托?)...
2023-11-11 C#/.NET开发问题
3

ASP.NET MVC 中的 <%: 和 <%= 有什么区别?
What is the difference between lt;%: and lt;%= in ASP.NET MVC?(ASP.NET MVC 中的 lt;%: 和 lt;%= 有什么区别?)...
2023-11-10 C#/.NET开发问题
0

标签系统的 linq 查询 - 搜索多个标签
linq query for tag system - search for multiple tags(标签系统的 linq 查询 - 搜索多个标签)...
2023-11-10 C#/.NET开发问题
0

论坛标签.实施它们的最佳方法是什么?
Forum tags. What is the best way to implement them?(论坛标签.实施它们的最佳方法是什么?)...
2023-11-10 C#/.NET开发问题
1

html 脚本标签未使用类型 javascript <script type="text
html script tag not using type javascript lt;script type=quot;text/htmlquot;gt;?(html 脚本标签未使用类型 javascript lt;script type=quot;text/htmlgt;gt;?)...
2023-11-10 C#/.NET开发问题
6

ASP.NET 控件到 HTML 标记等效
ASP.NET Control to HTML tag equivalent(ASP.NET 控件到 HTML 标记等效)...
2023-11-10 C#/.NET开发问题
32