[英]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.