9

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?

1
  • Web API is for RESTful web service. So yes it can be done and it's not a bad idea. Commented Aug 18, 2012 at 0:13

2 Answers 2

6

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; } 
Sign up to request clarification or add additional context in comments.

2 Comments

We get this: The requested resource does not support http method 'GET'.
Add an HttpGet attribute ([HttpGet]) above the method. @teenup
4

I 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; } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.