gpt4 book ai didi

c# - 从 MVC 4 调用 Web API 方法

转载 作者:太空宇宙 更新时间:2023-11-03 16:07:48 25 4
gpt4 key购买 nike

我有一个 MVC4 WebAPI 项目和一个 Controller 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 网络应用程序调用此 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 返回:

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 }

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

最佳答案

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

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

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

关于c# - 从 MVC 4 调用 Web API 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com