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.
This gives the response header:
- Status Code: 200
- Date: Fri, 06 Apr 2012 21:28:30 GMT
- X-AspNet-Version: 4.0.30319
- Transfer-Encoding: chunked
- Content-Disposition: attachment; filename=mytext.txt
- Connection: Close
- Pragma: no-cache
- Server: ASP.NET Development Server/22.214.171.124
- Content-Type: application/octet-stream
- Cache-Control: no-cache
- Expires: -1
And Body: Hello
When the browser gets this response, you will be prompted to download the file: mytext.txt.