BinaryResult for Asp.Net MVC

I was working with the latest drop of the asp.net mvc framework and had a need to stream a pdf back to the user… A quick glance around the System.Web.Mvc namespace only yielded ContentResult.  While that’s cool for string content, I needed something more flexible for binary data.  So I wrote the BinaryResult:

public class BinaryResult : ActionResult
{
    public byte[] Data { get; set; }
    public bool IsAttachment { get; set; }
    public string FileName { get; set; }
    public string ContentType { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = ContentType;
        if (!string.IsNullOrEmpty(FileName))
        {
            context.HttpContext.Response.AddHeader("content-disposition",
                ((IsAttachment) ? "attachment;filename=" : "inline;filename=") +
                FileName);
        }
        context.HttpContext.Response.BinaryWrite(Data);
    }
}

You can use this in your controllers to stream any type of binary data as the ActionResult for that controller.  So for my example, I call it like:

public ActionResult Download()
{
    Doc doc = new Doc();
    doc.Read(Server.MapPath("~/Sample.pdf"));
    using (MemoryStream stream = new MemoryStream())
    {
        doc.Save(stream);

        return new BinaryResult
                   {
                       ContentType = "application/pdf",
                       FileName = "Sample.pdf",
                       IsAttachment = true,
                       Data = stream.ToArray()
                   };
    }
}

btw, sorry if I’m reinventing the wheel with this, but Google gave no love when I tried searching for it

4 thoughts on “BinaryResult for Asp.Net MVC

  1. Looks OK, but it’s going to handle large files poorly. You should look into Response.TransmitFile and use that. Also, you might want to consider input stream to output stream buffering if you don’t use TransmitFile so you at least have the potential of NOT loading the entire file into an in-memory byte array. Your implementation is going to kill your web server as soon as a bunch of people start downloading 50mb files all at the same time.

Comments are closed.