Created
September 25, 2014 13:11
-
-
Save mattcanty/d2ea3d52dfdcaf587901 to your computer and use it in GitHub Desktop.
MVC4 ApiController Download FIle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using System.Net.Http; | |
using System.Net.Http.Headers; | |
using System.Web.Http; | |
namespace Web.Controllers | |
{ | |
//usage: /download/report | |
[RoutePrefix("download")] | |
public class DownloadController : ApiController | |
{ | |
[HttpGet("report")] | |
public HttpResponseMessage Report() | |
{ | |
using (var service = new Client()) | |
{ | |
var report = service.BuildReport(); | |
return DownloadResponse(report, "Report.csv"); | |
} | |
} | |
private static HttpResponseMessage DownloadResponse(string content, string fileName) | |
{ | |
var downloadContent = new StringContent(content); | |
var mediaType = new MediaTypeHeaderValue("application/octet-stream"); | |
var dispostition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; | |
downloadContent.Headers.ContentType = mediaType; | |
downloadContent.Headers.ContentDisposition = dispostition; | |
var result = new HttpResponseMessage(HttpStatusCode.OK) | |
{ | |
Content = downloadContent | |
}; | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how do i handle this stream in html page?