Force download of file from ASP.NET WebAPI

How to generate and download content as files from an ASP.NET WebApi action. This example is focused on text content. When returning a file, we actually utilize <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpresponsemessage(v=vs.110).aspx">HttpResponseMessage</a> for low level modification of http headers.

First we return HttpStatusCode.OK, then set the content to a StringContent, content could be set to many other things such as streams, etc. We then set the Content-Type to ‘application/octet-stream’, which means the downloaded file is associated with a program that can open/read the file. We then create a Content-Disposition type of ‘attachment’, which tells the browser to utilize a save-file dialog box to save the file. We use ContentDispositionHeaderValue class for that. ContentDisposition is null so we need to initialize and configure it.

Sample Code:

This gives the response header:

  1. Status Code: 200
  2. Date: Fri, 06 Apr 2012 21:28:30 GMT
  3. X-AspNet-Version: 4.0.30319
  4. Transfer-Encoding: chunked
  5. Content-Disposition: attachment; filename=mytext.txt
  6. Connection: Close
  7. Pragma: no-cache
  8. Server: ASP.NET Development Server/11.0.0.0
  9. Content-Type: application/octet-stream
  10. Cache-Control: no-cache
  11. Expires: -1

And Body: Hello

When the browser gets this response, you will be prompted to download the file: mytext.txt.