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.

 1using System.IO;
 2using System.Net;
 3using System.Net.Http;
 4using System.Net.Http.Headers;
 5using System.Text;
 6using System.Web.Http;
 7using System.Web.Http.Results;
 8
 9namespace WebApi2DownloadInMemoryFile.Controllers
10{
11    public class FileDownloadController : ApiController
12    {
13        public IHttpActionResult Get()
14        {
15            string someTextToSendAsAFile = "Hello world";
16            byte[] textAsBytes = Encoding.Unicode.GetBytes(someTextToSendAsAFile);
17
18            MemoryStream stream = new MemoryStream(textAsBytes);
19
20            HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
21            {
22                Content = new StreamContent(stream)
23            };
24            httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
25            {
26                FileName = "WebApi2GeneratedFile.txt"
27            };
28            httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
29
30            ResponseMessageResult responseMessageResult = ResponseMessage(httpResponseMessage);
31            return responseMessageResult;
32        }
33    }
34}

Download full source code

comments powered by Disqus

Related