aliyun / aliyun-oss-csharp-sdk

Aliyun OSS SDK for C#
MIT License
384 stars 206 forks source link

.NET CORE HttpClient Proxy #150

Open johnwanzhi opened 3 months ago

johnwanzhi commented 3 months ago

此处有个Bug,假设用户电脑中启用了VPN,则无法访问阿里云服务。正确的做法应该是:

  private HttpClient Create(bool setProxy)
  {
      HttpClientHandler httpClientHandler = new HttpClientHandler();
      HttpClient client = new HttpClient(httpClientHandler);
      if (setProxy)
      {
          this.SetProxy(httpClientHandler);
      }
      else
      {
          httpClientHandler.UseProxy = false;
      }

      client.Timeout = Configuration.ConnectionTimeout < 0 ? TimeSpan.FromDays(1) : TimeSpan.FromMilliseconds(Configuration.ConnectionTimeout);
      client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", Configuration.UserAgent);
      ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(HttpFactory.CheckValidationResult);
      return client;
  }

代码

可以尽快修复这个Bug吗?

johnwanzhi commented 3 months ago

我的建议是让调用者自己提供 HttpClientHandler 对象,例如:

  private HttpClient Create(bool setProxy)
  {
      HttpClientHandler httpClientHandler;

      if (Configuration.HttpClientHandler == null)
      {
          httpClientHandler = new HttpClientHandler();
          if (setProxy)
          {
              this.SetProxy(httpClientHandler);
          }
          else
          {
              httpClientHandler.UseProxy = false;
          }
      }
      else
      {
          httpClientHandler = Configuration.HttpClientHandler;
      }
      HttpClient client = new HttpClient(httpClientHandler);

      client.Timeout = Configuration.ConnectionTimeout < 0 ? TimeSpan.FromDays(1) : TimeSpan.FromMilliseconds(Configuration.ConnectionTimeout);
      client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", Configuration.UserAgent);
      ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(HttpFactory.CheckValidationResult);
      return client;
  }