Bia Securities

BinaryResult for Asp.Net MVC

by Jim Geurts on Jul.25, 2008

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 Comments for this entry

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...