Intermittent "Server cannot set content type after HTTP headers have been sent" error when downloading files via api call

133 Views Asked by At

The file has been successfully downloaded and show the images in the ui. However I'm getting an exception error "Exception Message: Server cannot set content type after HTTP headers have been sent. Stack Trace: at System.Web.HttpResponse.set_ContentType(String value)" in the logs. Sorry, this might be a duplicate question but it is still happening on my end with all the possible fixes I found online.

Note: Api call multiple times on a single page.

Here's the example code:

// send file to client
byte[] bytes = result.Image; - image bytes
Response.ClearHeaders();
Response.Clear();
Response.ClearContent(); 
Response.BufferOutput = true;
Response.Buffer = true;

Response.AppendHeader("Content-Length", bytes.Length.ToString()); 
Response.ContentType = "APPLICATION/OCTET-STREAM";

Response.BinaryWrite(bytes);
Response.Flush();
Response.End();

return Json(new { success = true, Message = "Image Successfully Render" }, "APPLICATION/OCTET-STREAM", JsonRequestBehavior.AllowGet);
0

There are 0 best solutions below