[英]How to download file from remote server with asp.net core?
我有一个 asp.net 核心 3 应用程序。
我尝试从地址为:123.456.789 的服务器下载日志文件。
有几点需要注意:
因此,请确保您获得了存储文件的正确路径
我建议您首先创建一个小型控制台应用程序以在本地下载文件(将其保存到 C:\Temp\file.txt),一旦您将其与 webapi 集成,找到正确的方法来检索 AppData 文件夹(其中不应该在会话中)
你想在这里做的是:
HttpClient
而不是WebClient
。 HttpClient
在各方面都更胜一筹。HttpClient
响应向FileStream
写入响应 streampublic async Task<IActionResult> UserLogs(string id)
{
// Set reasonable IP so HttpClient won't fail
string remoteFileUrl = "http://myuri.com/file.txt";
// Not sure what's happening here. Make sure it's pointing to reasonable
// location on machine.
// string localFileName = Path.Combine(_contextAccessor.HttpContext.Session.GetString("App_Data"), "C:\\inetpub\\logs\\LogFiles\\W3SVC15\\u_ex200621");
string localFileName = "C:\\downloads\\some_file.txt"
// Injecting via ASP.NET depenency injection is recommended however
var httpClient = new HttpClient();
var httpResponse = await httpClient.GetAsync(remoteFileUrl);
using (var fs = File.Create(localFileName))
{
httpResponse.Content.CopyToAsync(fs);
}
return View();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.