Downloading an in-memory file using Web Api 2

Download full source code

At first you think it’s going to be easy to download a file from Web Api, but as I discovered, it was not.

In my case I wanted to load data from the database, perform some processing and return a subset of the data as a file. This meant I needed to send something that was in memory back to the caller as a file; I was NOT loading a file from the disk.

For simplicity I will skip all the database work and processing and jump to the in-memory object and how to return that.

The code is fairly self explanatory.

using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using System.Web.Http.Results;

namespace WebApi2DownloadInMemoryFile.Controllers
    public class FileDownloadController : ApiController
        public IHttpActionResult Get()
            string someTextToSendAsAFile = "Hello world";
            byte[] textAsBytes = Encoding.Unicode.GetBytes(someTextToSendAsAFile);

            MemoryStream stream = new MemoryStream(textAsBytes);

            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
                Content = new StreamContent(stream)
            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                FileName = "WebApi2GeneratedFile.txt"
            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

            ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
            return responseMessageResult;

Download full source code

2 thoughts on “Downloading an in-memory file using Web Api 2

Leave a Reply

Your email address will not be published. Required fields are marked *