Quantcast
Channel: Mavention
Viewing all articles
Browse latest Browse all 627

How to serve a downloadable file from a MVC controller in Sitecore

$
0
0

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.

1
2
3
4
5
6
HttpContext.Response.ContentType = "Application/pdf";
HttpContext.Response.AddHeader("Content-Disposition", "attachment;filename=ourfile.pdf");
HttpContext.Response.Buffer = true;
HttpContext.Response.BinaryWrite(pdf.Bytes);
HttpContext.Response.Flush();
HttpContext.Response.Close();

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:

1
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:

1
2
3
publicActionResult GetPdf(Byte[] bytes) {
   returnFile(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.

Original blog location: Edwin's Journey


Viewing all articles
Browse latest Browse all 627

Trending Articles