I'm currently looking for a way to force download a file that is returned through a WebAPI controller.
I used http://www.shawnmclean.com/blog/2012/04/force-download-of-file-from-asp-net-webapi/ as a link.
On my client, I use the ajax GET call to send the object id and try to upload the file
exportList: (foo, callback) => path = '/api/export/id' path = path.replace("id", foo.id) $.ajax( url: path, dataType: 'text', success: (data) => callback(data) error: (data) => callback(false) )
On the server side, I have the above URI redirected to the method below
[AcceptVerbs("GET")] public HttpResponseMessage ExportList(int id) { string file = fooService.ExportList(id); if (file == null) { return Request.CreateResponse(HttpStatusCode.NoContent); } HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StringContent(file); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "List.csv"; return result; }
The fooService.ExportList method simply creates a csv string.
When viewing a request, it is returned to the client, there is a csv line in the response, but the client is not requested or loaded.
Can this be done correctly?
source share