【问题标题】:How to download file from remote server with asp.net core?如何使用 asp.net core 从远程服务器下载文件?
【发布时间】:2020-08-04 10:04:17
【问题描述】:

我有一个 asp.net core 3 应用程序。

我尝试从地址为 123.456.789 的服务器下载日志文件。

【问题讨论】:

    标签: c# asp.net-core webclient


    【解决方案1】:

    有几点需要注意:

    • 地址 123.456.789。对我来说看起来不那么有效,希望只是你发布的一个随机地址
    • 例外是您对应用程序执行的请求的 HttpContext,而不是您对 123.456.789 发出的请求。基本上在这里失败了 "_contextAccessor.HttpContext.Session.GetString("App_Data")"

    所以,请确保您获得了存储文件的正确路径

    我建议您首先创建一个小型控制台应用程序以在本地下载文件(将其保存到 C:\Temp\file.txt),一旦您将其与 webapi 集成,找到检索 AppData 的正确方法文件夹(不应在会话中)

    【讨论】:

    • 阅读异常,它说找不到目标目录 DirectoryNotFoundException: 找不到路径的一部分'C:\inetpub\logs\LogFiles\W3SVC15\u_ex200621.txt'。
    • 是的,我知道。但这是正确的地址。这是服务器上的地址:C:\inetpub\logs\LogFiles\W3SVC15,在该文件夹中有一个文件名为:u_ex200621.txt
    • 您需要确保该应用有权在该文件夹中写入,请先在您知道该应用可以写入的另一个目录中尝试
    【解决方案2】:

    你想在这里做的是:

    • 使用HttpClient 而不是WebClientHttpClient 在每个方面都优越 方式。
    • 将响应流从HttpClient 响应写入FileStream
    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();
    }
    

    【讨论】:

    • 它应该类似于https://stackoverflow.com/。基本上是 HTTP 有效的 URI
    • @NiceTobeBottleInfinity 似乎是 SSL 证书的问题。需要根据具体情况进行调试。
    • 所以这是我服务器上的位置:C:\inetpub\logs\LogFiles\W3SVC19
    • 你确定远程服务器上的文件被http暴露了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2020-02-29
    • 2013-03-07
    • 2013-08-30
    相关资源
    最近更新 更多