繁体   English   中英

从MVC4调用WebAPI方法

[英]Call WebAPI method from MVC4

我有一个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音频标签流式传输它。

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

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返回:

状态码:200,原因短语:“确定”,版本:1.1,内容:System.Net.Http.StreamContent,标题:{语法:no-cache连接:Close Cache-Control:no-cache日期:Thu,2013年9月5日15 :33:23 GMT服务器:ASP.NET服务器:开发服务器:Server / 10.0.0.0 X-AspNet版本:4.0.30319内容长度:13889内容处置:附件; filename = horse.ogg内容类型:application / octet-stream过期:-1}

因此,看起来内容确实是StreamContent,但它没有将其作为可保存文件返回。 现在的问题是,如何在直接调用API时反映行为? 任何建议,不胜感激。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM