简体   繁体   English

C# SSL连接无法建立,见内部异常

[英]C# The SSL connection could not be established, see inner exception

I tried to download files from site which is support TLS 1.3.我试图从支持 TLS 1.3 的站点下载文件。 I got error below.我在下面收到错误。

System.Net.Http.HttpRequestException: 'The SSL connection could not be established, see inner exception.' AuthenticationException: Authentication failed because the remote party sent a TLS alert: 'DecryptError'.

Also I tried to add: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12;我还尝试添加: ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12;

Also I tried other protocols but site is supporting tls 1.3 as i said above.我也尝试了其他协议,但正如我上面所说,网站支持 tls 1.3。 By the way, when I remove parallel foreach and run its working well.顺便说一下,当我删除并行 foreach 并运行时它运行良好。 However, I would like to download as a bulk.但是,我想批量下载。

I used Parallel.ForEach could it be related to this?我使用 Parallel.ForEach 可能与此有关吗?

            foreach (var directory in directories) 
            {
                if (directory.Contains($"C:\\Websites\\{domain}\\Uploads") || directory.Contains($"C:\\Websites\\{domain}\\CustomCss"))
                {
                    if (directory != null)
                    {
                        var directoryName = directory.Replace($"C:\\Websites\\{domain}\\", "/"); //String.Empty
                        if (directoryName.Contains("\\"))
                        {
                            directoryName = directoryName.Replace("\\", "/");
                        }
                        var createDirectory = await directoryClient.CreateDirectory(new CreateDirectoryRequest { FolderName = directoryName });

                        Parallel.ForEach(Directory.GetFiles(directory), new ParallelOptions { MaxDegreeOfParallelism = 15 }, async (item) =>
                        {
                            if (item != null)
                            {
                                var ms = new MemoryStream();
                                using (FileStream file = new FileStream(item, FileMode.Open, FileAccess.ReadWrite))
                                {
                                    using (ms = new MemoryStream())
                                    {
                                        file.CopyTo(ms);
                                        ms.ToArray();
                                    }
                                }

                                string filename = "";
                                Uri uri = new Uri(item);
                                if (uri.IsFile)
                                {
                                    filename = System.IO.Path.GetFileName(uri.LocalPath);
                                }
                                UploadFileResponse uploadResponse = new UploadFileResponse();

                                if (isImage(MimeMapping.MimeUtility.GetMimeMapping(item)))
                                {
                                    byte[] imageContent = await DownloadAndCompareImages(domain, directoryName + "/" + filename, "90");
                                    uploadResponse = await client.UploadFileAsync(new UploadFileRequest
                                    { FileContent = imageContent, FileName = "/" + directoryName + "/" + filename, ContentType = MimeMapping.MimeUtility.GetMimeMapping(ms.ToString()) });
                                }
                                else
                                {
                                    uploadResponse = await client.UploadFileAsync(new UploadFileRequest
                                    { FileContent = ms.ToArray(), FileName = "/" + directoryName + "/" + filename, ContentType = MimeMapping.MimeUtility.GetMimeMapping(ms.ToString()) });
                                }

                                if (!uploadResponse.IsError)
                                {
                                    finishedProcess++;
                                    fileCounter++;
                                    siteProcess.FinishedProcess = bucketName + " => Site is moving to MinIO...";
                                    siteProcess.FinishedCount = finishedProcess + "/" + totalFileFolder.ToString();
                                    siteProcess.MadePercentage = Convert.ToInt32((100 * (finishedProcess) / totalFileFolder));
                                }
                                else
                                {
                                    isError = true;
                                }

                                if (finishedProcess > totalFileFolder)
                                {
                                    finishedProcess = dataGridSites.SelectedItems.Count;
                                }
                            }
                        });
                    }
                }
            }
            return isError;
        }

Other function is:其他function为:

        private async Task<byte[]> DownloadAndCompareImages(string domain, string imgFilePath, string imgQuality)
        {
            using var httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36");

            Uri uriNormalPattern = new Uri($"https://{domain}/{imgFilePath}");

            var uriWithoutQuery = uriNormalPattern.GetLeftPart(UriPartial.Path); //
            var fname = System.IO.Path.GetFileName(uriWithoutQuery);

            var imageBytesNormal = await httpClient.GetByteArrayAsync(uriNormalPattern); //
            int imageWidth = GetImgWidth(imageBytesNormal);

            var imageBytesCloudFlare = await GetCloudFlareImg(domain, imageWidth, imgQuality, imgFilePath);

            if (imageBytesNormal.Length > imageBytesCloudFlare.Length)
            {
                return imageBytesCloudFlare;
            }
            else
            {
                return imageBytesNormal;
            }
        }

When using Parallel.ForEach a lot of requests are sent to the server in a short period of times.使用Parallel.ForEach时,会在短时间内将大量请求发送到服务器。 This might overwhelm the server, but also HttpClient is limited when accessing the same domain in parallel.这可能会使服务器不堪重负,而且HttpClient在并行访问同一域时也会受到限制。

In order to mitigate this, the following steps might help:为了缓解这种情况,以下步骤可能会有所帮助:

  • Instead of creating the HttpClient instance directly, you should use IHttpClientFactory to create the instances.您不应直接创建HttpClient实例,而应使用IHttpClientFactory来创建实例。 For details, see this link .有关详细信息,请参阅此链接 This avoids "resource exhaustion problems by pooling HttpMessageHandler instances".这避免了“通过池化 HttpMessageHandler 实例的资源耗尽问题”。
  • As you have already done, limiting the degree of parallelism can help avoid overwhelming the server.正如您已经做过的那样,限制并行度有助于避免服务器不堪重负。 The best value can only be guessed (maybe less than 15), but should be configurable in order to change the value in production without having to recompile.最佳值只能猜测(可能小于 15),但应该是可配置的,以便在无需重新编译的情况下更改生产中的值。
  • Given that the images won't change and that you need to request the same image repeatedly, you could cache the images in your service.鉴于图像不会改变并且您需要重复请求相同的图像,您可以将图像缓存在您的服务中。 This would reduce the load on the server that provides the images and speed up the process.这将减少提供图像的服务器上的负载并加快处理速度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法建立 SSL 连接,请参阅内部异常 - The SSL connection could not be established, see inner exception 如何修复“无法建立 SSL 连接,请参阅内部异常。” 尝试下载 osu! 化身 - How to fix "The SSL connection could not be established, see inner exception." when trying to download osu! avatar 如何修复“发生一个或多个错误。 (无法建立 SSL 连接,请参阅内部异常。)&#39;? - How to fix 'One or more errors occurred. (The SSL connection could not be established, see inner exception.)'? HTTPS .Net Core 3.1 导致“无法建立 SSL 连接,请参阅内部异常。” - HTTPS .Net Core 3.1 results in "The SSL connection could not be established, see inner exception." “无法建立 SSL 连接,请参阅内部异常。” 对于 POST 请求(.net 6) - "The SSL connection could not be established, see inner exception." For POST Request(.net 6) C# RestSharp 客户端证书获取异常“无法建立 SSL 连接” - C# RestSharp Client Certificate getting exception "The SSL connection could not be established" C# .NET Core 3.1 无法建立SSL连接 - C# .NET Core 3.1 The SSL connection could not be established 无法建立 SSL 连接 - The SSL connection could not be established 无法建立 SSL 连接 - SSL connection could not be established 调用SSPI失败,请参阅内部异常paho m2mqtt Dot.Net(c#)客户端SSL / TLS连接 - A call to SSPI failed, see inner exception paho m2mqtt Dot.Net(c#) client SSL/TLS connection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM