【发布时间】:2015-10-04 14:40:58
【问题描述】:
我看到this post 给出了使用WebClient 将文件上传到ftp 的简单想法。这很很简单,但我如何强制它使用SSL?
【问题讨论】:
我看到this post 给出了使用WebClient 将文件上传到ftp 的简单想法。这很很简单,但我如何强制它使用SSL?
【问题讨论】:
Edward Brey 的answer here 可能会回答您的问题。我不会提供我自己的答案,而是复制 Edward 所说的话:
你可以使用 FtpWebRequest;但是,这是相当低的水平。有一个更高级别的类 WebClient,它在很多场景下需要的代码要少得多;但是,它默认不支持 FTP/SSL。幸运的是,您可以通过注册自己的前缀使 WebClient 与 FTP/SSL 一起工作:
private void RegisterFtps()
{
WebRequest.RegisterPrefix("ftps", new FtpsWebRequestCreator());
}
private sealed class FtpsWebRequestCreator : IWebRequestCreate
{
public WebRequest Create(Uri uri)
{
FtpWebRequest webRequest = (FtpWebRequest)WebRequest.Create(uri.AbsoluteUri.Remove(3, 1)); // Removes the "s" in "ftps://".
webRequest.EnableSsl = true;
return webRequest;
}
}
完成此操作后,您几乎可以像平常一样使用 WebRequest,只是您的 URI 以“ftps://”而不是“ftp://”开头。一个警告是您必须指定方法,因为不会有默认方法。例如
// Note here that the second parameter can't be null.
webClient.UploadFileAsync(uploadUri, WebRequestMethods.Ftp.UploadFile, fileName, state);
【讨论】:
@MyName,否则我不会收到您的评论通知。再次感谢。
ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true;
EnableSsl 时,默认情况下客户端使用操作系统的公钥基础结构验证证书。请注意,如果您通过盲目接受任何服务器证书来绕过验证,您将容易受到中间人攻击。