Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server cannot set content type after HTTP headers have been sent

I get an error (Server cannot set content type after HTTP headers have been sent.) on the following code (ContentType line). What should I change?

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.

like image 806
GurdeepS Avatar asked Feb 20 '12 12:02

GurdeepS


People also ask

How do I change the Content-Type in an HTTP header?

To specify the content types of the request body and output, use the Content-Type and Accept headers. Indicates that the request body format is JSON. Indicates that the request body format is XML. Indicates that the request body is URL encoded.

What is Content-Type in HTTP header?

The Content-Type header is used to indicate the media type of the resource. The media type is a string sent along with the file indicating the format of the file. For example, for image file its media type will be like image/png or image/jpg, etc. In response, it tells about the type of returned content, to the client.

How do I enable HTTP headers?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.


2 Answers

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);
like image 169
Allen Avatar answered Sep 19 '22 17:09

Allen


Do you need to 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";

like image 27
Tawab Wakil Avatar answered Sep 18 '22 17:09

Tawab Wakil