【问题标题】:Restsharp: Underlying connecion has been closedRestsharp:基础连接已关闭
【发布时间】:2018-09-29 00:30:28
【问题描述】:

我在 Windows 服务中使用 RestSharp 客户端时遇到问题。 当 API 关闭时,连接将丢失。但是一旦 API 再次运行,其余客户端就会不断抛出相同的错误。 即使我设置了 RestClient 的新实例。

任何人有同样的问题和可行的解决方案或建议?

【问题讨论】:

  • 您有导致此问题的代码示例吗?

标签: c# rest restsharp


【解决方案1】:

我是路德维希的同事。 我们的应用程序启动并连接到 api, 应用程序继续运行并调用 api。 当 api 突然关闭(重新启动)时,我们的应用程序收到错误:底层连接已关闭:服务器关闭了预期保持活动状态的连接,我们调用 InitODataClient 和 ReadConfigAsync 函数重新创建restClient。 当 api 再次运行时,我们希望 RestClient 再次工作,但我们不断得到:底层连接已关闭。无法为 ssl/tls 建立安全通道 当我们重新启动我们的应用程序时,一切都会再次运行。 没有证书问题。 似乎创建一个新的 RestClient 对象使用旧的(无效的)连接 我们使用的一些代码:

private RestClient restClient;

    private void InitODataClient()
    {
        restClient = new RestClient(options.BaseUrl);
        restClient.AddDefaultHeader("Authorization", "Bearer " + options.AccessToken);
    }

    private async Task ReadConfigAsync()
    {
            var requestApplication = new RestRequest("Applications/" + Guid.Parse(applicationId));
            var response = await restClient.ExecuteGetTaskAsync<Application>(requestApplication);
//Here the response contains the underlying connection is closed error
    }

    public async Task RestartAsync()
    {
        Stop();
        do
        {
            try
            {
                Logger.Log("Trying to reconnect to the server in 5 seconds...");
                Thread.Sleep(5000);
                InitODataClient();
                ReadConfigAsync().Wait();
                break;
            }
            catch (Exception) { }
        }
        while (true);
    }

【讨论】:

    【解决方案2】:

    基本上,这似乎是 SSL/TLS 协商失败。为了确保这一点,在实例化 RestClient 之前,您可以设置 ServicePointManager.SecurityProtocol,如下例所示:

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
    restClient = new RestClient(options.BaseUrl);
    

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-12-02
      • 1970-01-01
      • 2017-06-16
      • 1970-01-01
      • 2018-03-29
      • 2019-03-01
      • 2013-12-22
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多