从MVC 4调用Web API方法

时间:2013-09-05 15:44:42

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api

我有一个MVC4 WebAPI项目,并且控制器FileController中包含此Get方法:

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

在浏览器localhost:9586/File/myfile.mp3中,它会将文件作为附件正确发送,您可以保存它。如果是音频文件,您可以从HTML5音频标签流式传输。

现在,我需要从WebAPI网络应用程序中调用此MVC4方法,基本上将其包装起来。它来了:

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

转到localhost:8493/File/DispatchFile/my.mp3返回:

  

StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.StreamContent,标题:{Pragma:no-cache连接:关闭缓存控制:无缓存日期:星期四,05 2013年9月15:33:23 GMT服务器:ASP.NET服务器:开发服务器:服务器/ 10.0.0.0 X-AspNet-版本:4.0.30319内容长度:13889内容 - 配置:附件; filename = horse.ogg Content-Type:application / octet-stream Expires:-1}

所以看起来内容确实是StreamContent,但它不会将其作为可保存文件返回。现在的问题是,如何在直接调用API时镜像行为?任何建议都非常赞赏。

1 个答案:

答案 0 :(得分:0)

我认为使用HttpClient.Result不是正确的方法。我认为您可能需要使用'Content'属性,然后调用ReadAsStreamAsync来获取WebAPI方法返回的文件流的句柄。此时,您应该能够将此流写入响应流,允许通过HTML5流式传输文件/音频。

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

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

相关问题