C# 发送 HTTP 标头后,服务器无法设置内容类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9360857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Server cannot set content type after HTTP headers have been sent
提问by GurdeepS
I get an error (Server cannot set content type after HTTP headers have been sent.) on the following code (ContentTypeline). What should I change?
我在以下代码(ContentType行)中收到错误(发送 HTTP 标头后服务器无法设置内容类型。)。我应该改变什么?
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + System.IO.Path.GetFileName(PervasiveConstants.DownloadZipLocation) + ";");
response.TransmitFile(PervasiveConstants.DownloadZipLocation);
response.Flush();
response.End();
This is within a Sharepoint 2010 webpart.
这是在 Sharepoint 2010 webpart 中。
回答by Dmitry Nogin
Have a look at HttpResponse.BufferOutput Property
看看 HttpResponse.BufferOutput 属性
http://msdn.microsoft.com/en-us/library/33cy25ty%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/33cy25ty%28v=vs.100%29.aspx
回答by Dhwanil Shah
Try setting response.BufferOutput = true;. Do this immediately after setting the responsevariable.
尝试设置response.BufferOutput = true;。设置response变量后立即执行此操作。
回答by Allen
I had a very similar issue to this on a webform. I solved this issue by adding the following code to my button in the code behind:
我在网络表单上遇到了与此非常相似的问题。我通过将以下代码添加到后面代码中的按钮解决了这个问题:
ScriptManager.GetCurrent(this).RegisterPostBackControl(btnPrint);
回答by José Silva
I had the same problem and the following solution solved the problem,
run a response.ClearHeaders();before run response.AddHeader(
我遇到了同样的问题,以下解决方案解决了问题,response.ClearHeaders();在运行前运行response.AddHeader(
回答by José Silva
This solution worked for me, add this line of code on the beginning of the method,
这个解决方案对我有用,在方法的开头添加这行代码,
Server.ClearError();
回答by Tawab Wakil
Do you needto set the content type? This solution should not be overlooked, because you may find your code to work perfectly without the need to explicitly define the content type for the type of response you are sending. So removing the following line should make the error go away, and may very well do so without introducing new problems (of course you'll want to test this against your scenario):
你需要设置内容类型?不应忽视此解决方案,因为您可能会发现您的代码可以完美运行,而无需为您发送的响应类型明确定义内容类型。因此,删除以下行应该会使错误消失,并且很可能不会引入新问题(当然,您需要针对您的场景进行测试):
response.ContentType = "text/plain";
response.ContentType = "text/plain";

