In our Sitecore project we had an application error being logged, every time when we served a download to our end users. We used the generally known HttpContext.Response approach, to stream the binary output of the file to the user.

HttpContext.Response.ContentType = "Application/pdf";
HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=ourfile.pdf");
HttpContext.Response.Buffer = true;

The pdf file was being send to the end users, but the combination of Sitecore, MVC and the controller logic, to serve the file, resulted in the following application error being logged:

System.Web.HttpUnhandledException (0x80004005): An unhandled exception occurred. ---> System.Web.HttpException (0x80004005): Server cannot set content type after HTTP headers have been sent.

It was quite complicated to solve the issue, as there was no option for us to interact with the HttpContext at an earlier moment in the code. Luckily our team member Corné found a different approach to send the file at this Stack Overflow Q&A. MVC allows to serve a file by returning a FileResult or FileStreamResult. Replacing the 6 lines of code with just this single line fixed the issue:

public ActionResult GetPdf(Byte[] bytes) {
   return File(bytes, "application/pdf", "ourfile.pdf");

If your project is based on MVC, remember that it’s now much easier to stream a file to the end user.