【问题标题】:FtpWebRequest ignores wrong password after previous successful connection using correct password上一次使用正确密码成功连接后,FtpWebRequest 忽略错误密码
【发布时间】:2017-11-03 12:05:12
【问题描述】:

在 C# 中使用 FtpWebRequest 类时遇到了问题。

当我第一次尝试使用正确的凭据将文件上传到 FTP 服务器,然后第二次尝试使用错误的凭据(用户名相同但密码错误)时,没有抛出异常并且文件仍然是 UPLOADED到 FTP 服务器。请考虑以下代码:

using System;
using System.Net;

internal class Program
{
    private static void Main(string[] args)
    {
        var uri = new Uri("ftp://ftp.dlptest.com/TestFile.txt");
        var method = WebRequestMethods.Ftp.UploadFile;

        //Here I'm uploading the test file using correct credentials
        var correctCredentials =
            new NetworkCredential("dlpuser@dlptest.com", "fwRhzAnR1vgig8s");
        DoFtpRequest(uri, correctCredentials, method);

        //Here I'm uploading the test file using wrong credentials.
        //I expect some exception to be thrown and the file not being
        //uploaded to the server, neither is the case.
        var wrongCredentials =
            new NetworkCredential("dlpuser@dlptest.com", "WRONG_PASWORD");
        DoFtpRequest(uri, wrongCredentials, method);
    }

    public static FtpWebResponse DoFtpRequest(
        Uri uri, NetworkCredential credentials, string method)
    {
        var request = (FtpWebRequest)WebRequest.Create(uri);
        request.Credentials = credentials;
        request.Method = method;
        return (FtpWebResponse)request.GetResponse();
    }
}

我在这里使用了一个公共 ftp 服务器 ftp://ftp.dlptest.com/,我在这里找到了 https://dlptest.com/ftp-test/,您可以使用它来测试此代码。

正如您首先看到的,我尝试使用正确的凭据上传文件,然后使用错误的凭据(使用相同的用户名但更改密码)。 但是文件仍然上传到服务器。如果我首先尝试使用错误的凭据,则会引发异常,并且一切都按预期工作。

你知道发生了什么吗?这是框架的错误吗?我有什么办法来处理这个问题,因为它会导致我现在正在开发的程序出现问题?

【问题讨论】:

    标签: c# .net ftp webrequest ftpwebrequest


    【解决方案1】:

    FtpWebRequest 在后台使用连接池。见FTP multiple files in C# without reestablishing connection。

    该连接池的键只有主机名、端口号、用户名和可选的连接组名。


    您的第二个请求重用了第一个请求的连接,并且永远不会使用错误的密码。这是因为这两个请求使用的是同一个连接池,因为它们的区别只是密码,而不是密钥的一部分。

    虽然,如果您交换请求,第一个请求不会成功,它的连接将关闭并且不会进入池。第二个请求必须从新连接开始,并且会使用正确的密码。


    要隔离请求,您可以:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      相关资源
      最近更新 更多