Skip to content

Instantly share code, notes, and snippets.

@mattcanty
Created September 25, 2014 13:11
Show Gist options
  • Save mattcanty/d2ea3d52dfdcaf587901 to your computer and use it in GitHub Desktop.
Save mattcanty/d2ea3d52dfdcaf587901 to your computer and use it in GitHub Desktop.
MVC4 ApiController Download FIle
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;
}
}
}
@willxiang
Copy link

how do i handle this stream in html page?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment