protected HttpMessageHandler CreateHttpClientHandler()

in src/Elastic.Transport/Components/TransportClient/HttpRequestInvoker.cs [250:319]


	protected HttpMessageHandler CreateHttpClientHandler(BoundConfiguration boundConfiguration)
	{
		var handler = new HttpClientHandler { AutomaticDecompression = boundConfiguration.HttpCompression ? GZip | Deflate : None, };

		// same limit as desktop clr
		if (boundConfiguration.ConnectionSettings.ConnectionLimit > 0)
			try
			{
				handler.MaxConnectionsPerServer = boundConfiguration.ConnectionSettings.ConnectionLimit;
			}
			catch (MissingMethodException e)
			{
				throw new Exception(MissingConnectionLimitMethodError, e);
			}
			catch (PlatformNotSupportedException e)
			{
				throw new Exception(MissingConnectionLimitMethodError, e);
			}

		if (!boundConfiguration.ProxyAddress.IsNullOrEmpty())
		{
			var uri = new Uri(boundConfiguration.ProxyAddress);
			var proxy = new WebProxy(uri);
			if (!string.IsNullOrEmpty(boundConfiguration.ProxyUsername))
			{
				var credentials = new NetworkCredential(boundConfiguration.ProxyUsername, boundConfiguration.ProxyPassword);
				proxy.Credentials = credentials;
			}
			handler.Proxy = proxy;
		}
		else if (boundConfiguration.DisableAutomaticProxyDetection) handler.UseProxy = false;

		// Configure certificate validation
		var callback = boundConfiguration.ConnectionSettings?.ServerCertificateValidationCallback;
		if (callback != null && handler.ServerCertificateCustomValidationCallback == null)
		{
			handler.ServerCertificateCustomValidationCallback = callback;
		}
		else if (!string.IsNullOrEmpty(boundConfiguration.ConnectionSettings.CertificateFingerprint))
		{
			handler.ServerCertificateCustomValidationCallback = (request, certificate, chain, policyErrors) =>
			{
				if (certificate is null && chain is null) return false;

				// The "cleaned", expected fingerprint is cached to avoid repeated cost of converting it to a comparable form.
				_expectedCertificateFingerprint ??= CertificateHelpers.ComparableFingerprint(boundConfiguration.ConnectionSettings.CertificateFingerprint);

				// If there is a chain, check each certificate up to the root
				if (chain is not null)
				{
					foreach (var element in chain.ChainElements)
					{
						if (CertificateHelpers.ValidateCertificateFingerprint(element.Certificate, _expectedCertificateFingerprint))
							return true;
					}
				}

				// Otherwise, check the certificate
				return CertificateHelpers.ValidateCertificateFingerprint(certificate, _expectedCertificateFingerprint);
			};
		}

		if (boundConfiguration.ClientCertificates != null)
		{
			handler.ClientCertificateOptions = ClientCertificateOption.Manual;
			handler.ClientCertificates.AddRange(boundConfiguration.ClientCertificates);
		}

		return handler;
	}