Asp.net mvc MVC控制器,从WebAPI获取一个文件并作为FileResult返回
我的控制器需要调用WebAPI方法,该方法将返回内容中包含pdf文件的HttpResponseMessage对象。我需要立即将此文件作为FileResult对象从控制器返回。 我曾尝试过许多解决方案,这些解决方案都是从各地找到的代码中组合而成的,但似乎所有的文件保存方法都是异步的,我在同一个控制器方法中立即将文件返回为FileResult时遇到了问题。 在这种情况下,最好的方法是什么 我尝试过的一些代码:Asp.net mvc MVC控制器,从WebAPI获取一个文件并作为FileResult返回,asp.net-mvc,file,download,asp.net-web-api2,fileresult,Asp.net Mvc,File,Download,Asp.net Web Api2,Fileresult,我的控制器需要调用WebAPI方法,该方法将返回内容中包含pdf文件的HttpResponseMessage对象。我需要立即将此文件作为FileResult对象从控制器返回。 我曾尝试过许多解决方案,这些解决方案都是从各地找到的代码中组合而成的,但似乎所有的文件保存方法都是异步的,我在同一个控制器方法中立即将文件返回为FileResult时遇到了问题。 在这种情况下,最好的方法是什么 我尝试过的一些代码: System.Threading.Tasks.Task tsk = response.Co
System.Threading.Tasks.Task tsk = response.Content.ReadAsFileAsync(localPath, true).ContinueWith(
(readTask) =>
{
Process process = new Process();
process.StartInfo.FileName = localPath;
process.Start();
});
await tsk;
return File(localPath, "application/octetstream", fileName);
这是我的主要想法,从响应内容中获取文件并将其作为FileResult返回。但这会导致等待tsk的访问被拒绝 您不必将文件以文件形式保存在磁盘上,只需处理如下流:
public async Task<FileResult> GetFile()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("https://www-asp.azureedge.net/v-2017-03-27-001/images/ui/asplogo-square.png");
var contentStream = await response.Content.ReadAsStreamAsync();
return this.File(contentStream, "application/png", "MyFile.png");
}
}
希望有帮助 您不必将文件以文件形式保存在磁盘上,只需处理如下流:
public async Task<FileResult> GetFile()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("https://www-asp.azureedge.net/v-2017-03-27-001/images/ui/asplogo-square.png");
var contentStream = await response.Content.ReadAsStreamAsync();
return this.File(contentStream, "application/png", "MyFile.png");
}
}
希望有帮助 你能分享你已经尝试使用的代码吗?这是一个混乱,我不知道要添加什么。。。我会添加一些代码。你能分享你已经尝试使用的代码吗?这是一个混乱,我不知道要添加什么。。。我会添加一些代码。我把它弄得太复杂了!谢谢你,阿德里安!我把事情弄得太复杂了!谢谢你,阿德里安!