2

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.mp3it 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.

4

1 回答 1

0

我相信在这里使用 HttpClient.Result 不是正确的方法。我认为您可能需要使用“内容”属性,然后调用 ReadAsStreamAsync 来获取 WebAPI 方法返回的文件流的句柄。此时,您应该能够将此流写入响应流,从而允许下载文件/通过 HTML5 流式传输音频。

有关使用 HttpClient 获取文件的示例,请参见此处(该链接显示了如何处理大文件,但我相信那里使用的方法是您需要做的):

http://developer.greenbutton.com/downloading-large-files-with-the-net-httpclient/

于 2013-10-22T21:41:27.283 回答