Using regular Controller I could do it by returning FileResult. The same doesn't seem to work with ApiController. Can it be done? Is it even a right thing to do?
2 Answers
Try this.
[HttpGet] public HttpResponseMessage Get() { var file = HttpContext.Current.Server.MapPath("~/Images/accent.png"); var stream = new FileStream(file, FileMode.Open); var content = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(stream) }; content.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return content; } 2 Comments
teenup
We get this:
The requested resource does not support http method 'GET'.Mike Marks
Add an
HttpGet attribute ([HttpGet]) above the method. @teenupI have this working thanks to this question.
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 disposition= new ContentDispositionHeaderValue("attachment") { FileName = fileName }; downloadContent.Headers.ContentType = mediaType; downloadContent.Headers.ContentDisposition = disposition; var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = downloadContent }; return result; } } }