簡體   English   中英

如何使用 asp.net 內核從遠程服務器下載文件?

[英]How to download file from remote server with asp.net core?

我有一個 asp.net 核心 3 應用程序。

我嘗試從地址為:123.456.789 的服務器下載日志文件。

有幾點需要注意:

  • 地址 123.456.789。 對我來說看起來不是那么有效,希望只是您發布的隨機地址
  • 例外是您對應用程序執行的請求的 HttpContext,而不是您對 123.456.789 發出的請求。 基本上在這里失敗“_contextAccessor.HttpContext.Session.GetString("App_Data")”

因此,請確保您獲得了存儲文件的正確路徑

我建議您首先創建一個小型控制台應用程序以在本地下載文件(將其保存到 C:\Temp\file.txt),一旦您將其與 webapi 集成,找到正確的方法來檢索 AppData 文件夾(其中不應該在會話中)

你想在這里做的是:

  • 使用HttpClient而不是WebClient HttpClient在各方面都更勝一籌。
  • HttpClient響應向FileStream寫入響應 stream
public 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM