Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从MVC4调用WebAPI方法_C#_Asp.net Mvc_Asp.net Mvc 4_Asp.net Web Api - Fatal编程技术网

C# 从MVC4调用WebAPI方法

C# 从MVC4调用WebAPI方法,c#,asp.net-mvc,asp.net-mvc-4,asp.net-web-api,C#,Asp.net Mvc,Asp.net Mvc 4,Asp.net Web Api,我有一个mvc4webapi项目,还有一个控制器FileController,其中包含这个Get方法: public HttpResponseMessage Get(string id) { if (String.IsNullOrEmpty(id)) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File Name Not Specified"); HttpResponseMessage

我有一个
mvc4webapi
项目,还有一个控制器
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
audio标签流式传输它

现在,我需要从一个
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,标题:{Pragma:无缓存连接:关闭缓存控制:无缓存日期:2013年9月5日星期四15:33:23 GMT服务器:ASP.NET服务器:开发服务器:服务器/10.0.0.0 X-AspNet-Version:4.0.30319内容长度:13889内容处置:附件;文件名=horse.ogg内容类型:应用程序/八位字节流过期:-1}


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

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

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


我不明白!你想要流媒体还是提供下载?