Wednesday, 15 October 2008

Alternative HTTP Output

Websites are tricky fellows. They'll churn out HTML output all day long without any thought or consideration to other mime outputs. If you want your ASP.Net website to chuck out other response types – then use the Http Response Stream as below

For PDF
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "application/pdf";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ePIMSDataExportReport.pdf");
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);
For Excel
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=ePIMSDataExportReport.xls");
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, bytes.Length);

Thus easy to extent to other mime types such as images and video and so forth. Of course you'll need a source of bytes – e.g. from a Sql Server Report

byte[] bytes = report.Render(
"PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings);

But once you have that – it’s in the pool kids and away you go.

No comments: