【问题标题】:C# : the underlying connection was closed an unexpected error occurred on a sendC#:底层连接已关闭,发送时发生意外错误
【发布时间】:2020-10-29 09:36:44
【问题描述】:

我正在使用 API,我必须在这些 API 上发送请求以获取身份验证密钥。我尝试了很多方法,但总是遇到如下相同的异常:

底层连接已关闭,发送时发生意外错误。

这是我的参考代码:

 public AuthTokenReponse GetAuthToken(IClientConfiguration clientConfiguration)
        {
            try
            {
                _logger.Info($"Getting Authentication Token");
                var client = new RestClient(_portalConfiguration.ApiAuthHostUrl);
                client.Proxy = new WebProxy();
                var request = new RestRequest(Method.POST);

                ServicePointManager.Expect100Continue = true;
                ServicePointManager.DefaultConnectionLimit = 9999;
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3;

                request.AddHeader("client_id", clientConfiguration.ApiClientId);
                request.AddHeader("client_secret", clientConfiguration.ApiClientSecret);

                request.AddHeader("Gstin", clientConfiguration.ApiGstin);
                request.AddHeader("user_name", clientConfiguration.ApiUserName);
                request.AddHeader("Content-Type", "application/json; charset=utf-8");
                request.RequestFormat = DataFormat.Json;

                var obj = new AuthRequestDto();
                var appKey = GenerateAppKey();

                obj.Data = new AuthRequestDto.DataDto
                {
                    UserName = clientConfiguration.ApiUserName,
                    Password = EncryptAsymmetric(clientConfiguration.ApiPassword, clientConfiguration.ApiPublicKey),
                    AppKey = Encrypt(appKey, clientConfiguration.ApiPublicKey),
                    ForceRefreshAccessToken = true
                };


                request.AddJsonBody(new
                {
                    data = obj.Data
                });

                _logger.Error($"Request Json : {JsonConvert.SerializeObject(request)}");


                IRestResponse response = client.Execute(request);

                //Here I'm getting the error in my Log file.
                _logger.Error($"Response Error {response.ErrorMessage}");
                _logger.Error($"Response Content {response.Content}");

                if (response != null && response.StatusCode == HttpStatusCode.OK)
                {
                    var result = JsonConvert.DeserializeObject<AuthTokenReponse>(response.Content);

                    if (result.Status > 0)
                    {
                        result.SekToken = DecryptBySymmetricKey(result.Data.Sek, appKey);

                        return result;
                    }
                    _logger.Error($"Error while getting auth token {response.Content} {response.StatusCode}");
                }
                else if (response != null)
                {
                    _logger.Error($"Error while getting auth token {response.Content} Status Code: {response.StatusCode}");
                }
                else
                {
                    _logger.Error($"Error while getting auth token {response.Content} , Reason unknown.");

                }



                return null;

            }
 catch (Exception ex)
            {
                _logger.Error($"Error while getting auth token", ex);

                return null;
            }

        }

我已经尝试过的选项:

  1. 清除缓存
  2. 添加安全协议

如果您有任何解决方案,请告诉我。

【问题讨论】:

  • 尝试删除:SecurityProtocolType.Tls |安全协议类型.Tls11。 TLS 1.0 和 1.1 不再被允许,可能会导致异常。
  • @jdweng 试过了,但没用
  • 该错误看起来不像是身份验证错误。获取状态码。如果您收到状态代码,则表示身份验证已完成,并且服务器不喜欢帖子中的设置。添加:_logger.Error($"响应状态码{response.StatusCode}");
  • 状态码显示为 0
  • 失败发生需要多长时间?如果未找到代理,将发生 30 秒超时。如果错误发生在发现代理之前。检查证书中的加密密钥并查看它是否对 TLS 1.2/1.3 有效(请参阅en.wikipedia.org/wiki/Transport_Layer_Security)。您使用的是什么内核/操作系统?内核可能较旧且不支持 TLS 1.2/1.3

标签: c# api server httpwebrequest rest


【解决方案1】:

一切都很好,客户端服务器有一个限制,即调用 API 时使用的每个 IP 都需要在其门户上注册。由于 IP 未注册而引发错误。

因此,如果有人遇到类似问题,请也尝试此解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2015-11-22
    相关资源
    最近更新 更多