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.
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.
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.
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.
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);
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With