I have an MVC4 WebAPI
project and have a controller FileController
that has this Get method in it:
public HttpResponseMessage Get(string id)
{
if (String.IsNullOrEmpty(id))
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File Name Not Specified");
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
var stream = fileService.GetFileStream(id);
if (stream == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "File Not Found");
}
response.Content = new StreamContent(stream);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = id;
return response;
}
In the browser going to localhost:9586/File/myfile.mp3
it dispatches the file correctly as an attachment and you can save it. If it is an audio file, you can stream it from the HTML5
audio tag.
Now, I need to call this WebAPI
method from an MVC4
web app, basically wrapping it. Here it comes:
public HttpResponseMessage DispatchFile(string id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8493/");
HttpResponseMessage response = client.GetAsync("api/File/"+id).Result;
return response;
}
Going to localhost:8493/File/DispatchFile/my.mp3
returns:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers: { Pragma: no-cache Connection: Close Cache-Control: no-cache Date: Thu, 05 Sep 2013 15:33:23 GMT Server: ASP.NET Server: Development Server: Server/10.0.0.0 X-AspNet-Version: 4.0.30319 Content-Length: 13889 Content-Disposition: attachment; filename=horse.ogg Content-Type: application/octet-stream Expires: -1 }
So it looks like the Content is indeed StreamContent, but it doesn't return it as a saveable file. Now the question is, how to mirror the behavior when calling the API directly? Any suggestions much appreciated.