I am trying to get my ASP.Net 5 MVC 6 WebAPI project to output a file in response to an HttpGET request.
A file from the Azure Files share, but can be any stream containing a binary file.
It seems to me that MVC serializes the response object and returns the received JSON, rather than returning the response object itself.
Here is my controller method:
[HttpGet] [Route("GetFile")] public HttpResponseMessage GetFile(string Username, string Password, string FullName) { var client = new AzureFilesClient.AzureFilesClient(Username, Password); Stream azureFileStream = client.GetFileStream(FullName).Result; var fileName = Path.GetFileName(FullName); using (HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK)) { response.Content = new StreamContent(azureFileStream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; return response; } }
The GetFileStream method on AzureFilesClient is present here, although the stream source can be any content from the binary:
public async Task<Stream> GetFileStream(string fileName) { var uri = new Uri(share.Uri + "/" + fileName); var file = new CloudFile(uri, credentials); using (var stream = new MemoryStream()) { await file.DownloadToStreamAsync(stream); stream.Seek(0, SeekOrigin.Begin); return stream; } }
Edit: Here is a sample JSON response:
{ "Version": { "Major": 1, "Minor": 1, "Build": -1, "Revision": -1, "MajorRevision": -1, "MinorRevision": -1 }, "Content": { "Headers": [ { "Key": "Content-Type", "Value": [ "application/octet-stream" ] }, { "Key": "Content-Disposition", "Value": [ "attachmentx; filename=\"samplefile.docx\"" ] } ] }, "StatusCode": 200, "ReasonPhrase": "OK", "Headers": [], "RequestMessage": null, "IsSuccessStatusCode": true }