简体   繁体   English

无法在 dotNet Core 中建立 SSL 连接

[英]The SSL connection could not be established in dotNet Core

In my microservice i am calling a third party api.在我的微服务中,我正在调用第三方 API。

https://sms.partname.in/mspProducerM/sendSMS?queryParam

it's working fine but sometime i am getting following error.它工作正常,但有时我会遇到以下错误。

SmsClient ? - Connection refused - System.Net.Http.HttpRequestException: Connection refused
 ---> System.Net.Sockets.SocketException (111): Connection refused
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean allowHttp2, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean doRequestAuth, CancellationToken cancellationToken)
   at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)

I am unable to figure out the root cause.我无法找出根本原因。 Should i bypass the certificate ?我应该绕过证书吗? code:-代码:-

private static HttpClient _httpClient = new HttpClient();
        public static async Task<string> SendAsync(Uri url)
        {
            try
            {
                string result = string.Empty;
                using (var response = await _httpClient.GetAsync(url).ConfigureAwait(false))
                {
                    if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error occurred while sending sms urlLink:{url}", ex);
                throw;
            }
        }

There are a few small tweaks that you can try:您可以尝试一些小的调整:

  • You should only create an HttpClient once.您应该只创建一次 HttpClient。
    Depending on how your class is being used (where you initialized the _httpClient ), this is not the case.根据您的类的使用方式(您初始化_httpClient ),情况并非如此。
  • I would change your if-statement if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK) and use one of the built-in features.我会更改您的 if 语句if (response != null && response.StatusCode == System.Net.HttpStatusCode.OK)并使用其中一项内置功能。
    Either use response.IsSuccessStatusCode or response.EnsureSuccessStatusCode() .使用response.IsSuccessStatusCoderesponse.EnsureSuccessStatusCode() The latter will throw an exception in case the status code is not successful.后者将在状态码不成功的情况下抛出异常。

An other thing to take into account, is that HTTP calls will fail sometimes.另一件需要考虑的事情是 HTTP 调用有时会失败。 This can happen for multiple reasons: network timeout, rate limiting, ... .发生这种情况的原因有多种:网络超时、速率限制……。
Perhaps you need to implement some resilience.也许您需要实现一些弹性。 For instance, does it work if you try the same HTTP call again, after waiting for 1 second?例如,如果您在等待 1 秒后再次尝试相同的 HTTP 调用,它是否有效? If so, you can easily implement this with Polly .如果是这样,您可以使用Polly轻松实现这一点。

However, I would strongly advise that you start using the built-in features of .NET Core.但是,我强烈建议您开始使用 .NET Core 的内置功能。 Managing an HttpClient can be tricky sometimes.管理 HttpClient 有时会很棘手。 But .NET Core can manage this automatically, by using the IHttpClientFactory .但是 .NET Core 可以通过使用IHttpClientFactory自动管理它。 You can even implement resilience using a few extension methods.您甚至可以使用一些扩展方法来实现弹性

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM