首页 > 解决方案 > 使用代理支持对 HttpClient 执行基本身份验证

问题描述

我正在尝试从防火墙后面的服务器访问一些 Internet 资源。每次我提出请求时,我的代理都会收到错误消息。它说我没有经过身份验证(HTTP 407 错误代码)。但我正在使用下一个代码(我想它支持代理)

public class ProxyHttpClientFactory: HttpClientFactory {
  private readonly ICredentials _credentials;
  private readonly IWebProxy _proxy;

  public ProxyHttpClientFactory(ProxyOptions options) {
    _credentials = new NetworkCredential(options.Login, options.Password, options.ProxyUri);
    _proxy = new WebProxy {
      Address = new Uri(options.ProxyUri),
      Credentials = _credentials
    };
  }

  protected override HttpMessageHandler CreateHandler(CreateHttpClientArgs args) {
    return new CustomHandler(_proxy, _credentials);
  }
}

public CustomHandler(IWebProxy proxy, ICredentials credentials) {
  UseProxy = true;
  Proxy = proxy;
  Credentials = credentials;
  SslProtocols = SslProtocols.Tls12;
  UseCookies = false;
  ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>true;
}

标签: c#proxyhttp-proxy

解决方案


推荐阅读