繁体   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