BinaryResult for Asp.Net MVC

I was working with the latest drop of the 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.ContentType = ContentType;
        if (!string.IsNullOrEmpty(FileName))
                ((IsAttachment) ? "attachment;filename=" : "inline;filename=") +

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();
    using (MemoryStream stream = new MemoryStream())

        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.