public HttpClient GetHttpClient(string baseUrl, string socks = null, bool sslVerify = true) { SocketsHttpHandler socketsHttpHandler = new SocketsHttpHandler() { UseProxy = !string.IsNullOrEmpty(socks), Proxy = new WebProxy(socks, false) }; if (!sslVerify) { socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback += (a, b, c, d) => true; } HttpClient httpClient = new HttpClient(socketsHttpHandler) { BaseAddress = new Uri(baseUrl) }; httpClient.DefaultRequestHeaders.Clear(); httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "deflate"); httpClient.DefaultRequestHeaders.Add("Accept", "application/json, text/plain, */*"); httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); httpClient.DefaultRequestHeaders.Add("User-Agent", "Twicepower-Unifi-Client"); return(httpClient); }
/// <inheritdoc/> public HttpMessageInvoker CreateClient(ForwarderHttpClientContext context) { if (CanReuseOldClient(context)) { Log.ClientReused(_logger, context.ClusterId); return(context.OldClient !); } var handler = new SocketsHttpHandler { UseProxy = false, AllowAutoRedirect = false, AutomaticDecompression = DecompressionMethods.None, UseCookies = false, #if NET6_0_OR_GREATER ActivityHeadersPropagator = new ReverseProxyPropagator(DistributedContextPropagator.Current) #endif // NOTE: MaxResponseHeadersLength = 64, which means up to 64 KB of headers are allowed by default as of .NET Core 3.1. }; ConfigureHandler(context, handler); var middleware = WrapHandler(context, handler); Log.ClientCreated(_logger, context.ClusterId); return(new HttpMessageInvoker(middleware, disposeHandler: true)); }
public Launcher(ISteam?steam, IUniqueIdCache uniqueIdCache, ISettings settings) { this.steam = steam; this.uniqueIdCache = uniqueIdCache; this.settings = settings; ServicePointManager.Expect100Continue = false; #if NET6_0_OR_GREATER var sslOptions = new SslClientAuthenticationOptions() { CipherSuitesPolicy = new CipherSuitesPolicy(new[] { TlsCipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 }) }; var handler = new SocketsHttpHandler { UseCookies = false, SslOptions = sslOptions, }; #else var handler = new HttpClientHandler { UseCookies = false, }; #endif this.client = new HttpClient(handler); }
public void Configure(DaemonEndpointConfig[] endPoints, string digestAuthRealm = null) { Contract.RequiresNonNull(endPoints, nameof(endPoints)); Contract.Requires <ArgumentException>(endPoints.Length > 0, $"{nameof(endPoints)} must not be empty"); this.endPoints = endPoints; // create one HttpClient instance per endpoint that carries the associated credentials httpClients = endPoints.ToDictionary(endpoint => endpoint, endpoint => { var handler = new SocketsHttpHandler { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip, }; if (!string.IsNullOrEmpty(endpoint.User)) { handler.Credentials = new NetworkCredential(endpoint.User, endpoint.Password); handler.PreAuthenticate = true; } if ((endpoint.Ssl || endpoint.Http2) && !endpoint.ValidateCert) { handler.SslOptions = new SslClientAuthenticationOptions { RemoteCertificateValidationCallback = ((sender, certificate, chain, errors) => true), }; } return(new HttpClient(handler)); }); }
public async Task ConnectTimeout_TimesOutSSLAuth_Throws() { var releaseServer = new TaskCompletionSource(); await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var handler = new SocketsHttpHandler()) using (var invoker = new HttpMessageInvoker(handler)) { handler.ConnectTimeout = TimeSpan.FromSeconds(1); var sw = Stopwatch.StartNew(); await Assert.ThrowsAnyAsync <OperationCanceledException>(() => invoker.SendAsync(TestAsync, new HttpRequestMessage(HttpMethod.Get, new UriBuilder(uri) { Scheme = "https" }.ToString()) { Version = UseVersion }, default)); sw.Stop(); Assert.InRange(sw.ElapsedMilliseconds, 500, 60_000); releaseServer.SetResult(); } }, server => releaseServer.Task); // doesn't establish SSL connection }
public MyHandler() { InnerHandler = new SocketsHttpHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip }; }
internal static HttpMessageHandler CreateDefaultHttpMessageHandler(IWebProxy webProxy, Uri baseUri, int connectionLeaseTimeoutMilliseconds) { #pragma warning disable CA2000 // Dispose objects before losing scope (object is returned by this method, so the caller is responsible for disposing it) #if NETCOREAPP && !NETCOREAPP2_0 && !NETCOREAPP1_0 && !NETCOREAPP1_1 // SocketsHttpHandler is only available in netcoreapp2.1 and onwards var httpMessageHandler = new SocketsHttpHandler(); httpMessageHandler.SslOptions.EnabledSslProtocols = TlsVersions.Instance.Preferred; #else var httpMessageHandler = new HttpClientHandler(); #if !NET451 httpMessageHandler.SslProtocols = TlsVersions.Instance.Preferred; httpMessageHandler.CheckCertificateRevocationList = TlsVersions.Instance.CertificateRevocationCheck; #endif #endif #pragma warning restore CA2000 // Dispose objects before losing scope if (webProxy != DefaultWebProxySettings.Instance) { httpMessageHandler.UseProxy = webProxy != null; httpMessageHandler.Proxy = webProxy; } ServicePointHelpers.SetLimits(httpMessageHandler, baseUri, connectionLeaseTimeoutMilliseconds); return(httpMessageHandler); }
/// <summary> /// 5 分鐘內,會共用一條連線。 /// </summary> public async Task <IActionResult> Demo1() { // Ref: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.socketshttphandler?view=netcore-3.1 var socketsHandler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromMinutes(10), PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5), MaxConnectionsPerServer = 10 }; var client = new HttpClient(socketsHandler); HttpResponseMessage response = null; for (var i = 0; i < 5; i++) { response = await client.GetAsync("https://www.google.com"); await Task.Delay(TimeSpan.FromSeconds(2)); } response.EnsureSuccessStatusCode(); var result = response.Content.ReadAsStringAsync(); return(Ok(result)); }
/// <summary> /// 60 秒內,最多 2 條連線。 /// </summary> /// <returns></returns> public async Task <IActionResult> Demo3() { var socketsHandler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromSeconds(60), PooledConnectionIdleTimeout = TimeSpan.FromSeconds(60), MaxConnectionsPerServer = 2 }; var client = new HttpClient(socketsHandler); HttpResponseMessage response = null; for (var i = 0; i < 5; i++) { response = await client.GetAsync("https://www.google.com"); await Task.Delay(TimeSpan.FromSeconds(2)); } response.EnsureSuccessStatusCode(); var result = response.Content.ReadAsStringAsync(); return(Ok(result)); }
protected QBittorrentClient CreateClient() { #if NETFRAMEWORK || NETCOREAPP2_0 var handler = new HttpClientHandler { Proxy = GetProxy(), UseDefaultCredentials = NetworkSettings.UseDefaultCredentials, Credentials = GetCredentials(), PreAuthenticate = true }; if (NetworkSettings.IgnoreCertificateErrors) { handler.ServerCertificateCustomValidationCallback = (message, cert, chain, error) => true; } #else var handler = new SocketsHttpHandler { Proxy = GetProxy(), Credentials = GetCredentials(), PreAuthenticate = true }; if (NetworkSettings.IgnoreCertificateErrors) { handler.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, error) => true; } #endif return(new QBittorrentClient(new Uri(Url, UriKind.Absolute), handler, true)); }
static async Task Authenticate(String uri, bool useNtlm = true) { var handler = new SocketsHttpHandler(); var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("Accept", "*/*"); var ntlm = new Ntlm(nc); string msg = ntlm.CreateNegotiateMessage(spnego: !useNtlm); var message = new HttpRequestMessage(HttpMethod.Get, uri); message.Headers.Add("Authorization", ntlm.CreateNegotiateMessage(spnego: !useNtlm)); HttpResponseMessage response = await client.SendAsync(message, default); if (response.StatusCode == HttpStatusCode.Unauthorized) { foreach (AuthenticationHeaderValue header in response.Headers.WwwAuthenticate) { string blob = ntlm.ProcessChallenge(header); if (!string.IsNullOrEmpty(blob)) { message = new HttpRequestMessage(HttpMethod.Get, uri); message.Headers.Add("Authorization", blob); response = await client.SendAsync(message, default); } } } Console.WriteLine(response); }
private static SocketsHttpHandler CreateHandler(GlobalCacheKey key) { var handler = new SocketsHttpHandler { Proxy = key.Proxy, UseProxy = key.Proxy != null, ConnectTimeout = key.ConnectionTimeout, AllowAutoRedirect = key.AllowAutoRedirect, PooledConnectionIdleTimeout = key.ConnectionIdleTimeout, PooledConnectionLifetime = key.ConnectionLifetime, MaxConnectionsPerServer = key.MaxConnectionsPerEndpoint, AutomaticDecompression = DecompressionMethods.None, MaxResponseHeadersLength = 64 * 1024, MaxAutomaticRedirections = 3, UseCookies = false, SslOptions = { CertificateRevocationCheckMode = X509RevocationMode.NoCheck, RemoteCertificateValidationCallback = (_, __,___, ____) => true, } }; key.CustomTuning?.Invoke(handler); return(handler); }
/// <summary> /// /// </summary> /// <param name="verifySSL">is false, SSL-verification is disabled</param> /// <param name="timeout">timeout in seconds</param> /// <returns>a new `HttpClient` instance</returns> public static HttpClient CreateHttpClient(bool verifySSL, int timeout) { if (verifySSL) { var handler = new SocketsHttpHandler() { // uncomment this to enable keep-alive after moving to netcore5 // ConnectCallback = s_defaultConnectCallback, }; HttpClient httpClient = new HttpClient(handler); httpClient.Timeout = TimeSpan.FromSeconds(timeout); return(httpClient); } else { // If we don't want to verify SSL certificate (from the Server), we need to // specifically attach a `HttpClientHandler` to `HttpClient` for accepting // any certificate from the server. This is useful for testing purposes, but // should not be used in production. var sslOptions = new SslClientAuthenticationOptions { // Leave certs unvalidated for debugging RemoteCertificateValidationCallback = delegate { return(true); }, }; var handler = new SocketsHttpHandler() { // uncomment this to enable keep-alive after moving to netcore5 // ConnectCallback = s_defaultConnectCallback, SslOptions = sslOptions }; HttpClient httpClient = new HttpClient(handler); httpClient.Timeout = TimeSpan.FromSeconds(timeout); return(httpClient); } }
// NOTE: this method replicates the logic that the base ServiceClient uses except that it doesn't insert the RetryDelegatingHandler // and it does insert the WatcherDelegatingHandler. we don't want the RetryDelegatingHandler because it has a very broad definition // of what requests have failed. it considers everything outside 2xx to be failed, including 1xx (e.g. 101 Switching Protocols) and // 3xx. in particular, this prevents upgraded connections and certain generic/custom requests from working. private void CreateHttpClient(DelegatingHandler[] handlers, KubernetesClientConfiguration config) { #if NET5_0_OR_GREATER FirstMessageHandler = HttpClientHandler = new SocketsHttpHandler { KeepAlivePingPolicy = HttpKeepAlivePingPolicy.WithActiveRequests, KeepAlivePingDelay = TimeSpan.FromMinutes(3), KeepAlivePingTimeout = TimeSpan.FromSeconds(30), }; HttpClientHandler.SslOptions.ClientCertificates = new X509Certificate2Collection(); #else FirstMessageHandler = HttpClientHandler = new HttpClientHandler(); #endif if (handlers != null) { for (int i = handlers.Length - 1; i >= 0; i--) { DelegatingHandler handler = handlers[i]; while (handler.InnerHandler is DelegatingHandler d) { handler = d; } handler.InnerHandler = FirstMessageHandler; FirstMessageHandler = handlers[i]; } } HttpClient = new HttpClient(FirstMessageHandler, false) { Timeout = Timeout.InfiniteTimeSpan, }; }
static async Task Main(string[] args) { AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true); AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true); try { var handler = new SocketsHttpHandler(); var httpClient = new HttpClient(handler); var options = new GrpcChannelOptions { HttpClient = httpClient, DisposeHttpClient = true }; var channel = GrpcChannel.ForAddress("https://ttsl.tech/", options); var client = new Weather.Weather.WeatherClient(channel); var weatherService = new GrpcWeatherForecastService(client); var result = await weatherService.GetWeather(); } catch (Exception e) { Console.WriteLine(e); throw; } }
internal static void CreateHttpClient() { var handler = new SocketsHttpHandler { ConnectCallback = async(context, cancellationToken) => { // based of src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/HttpConnectionPool.cs#L1338 var socket = new Socket(SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; socket.Bind(new IPEndPoint(IPAddress.Any, 0)); // IPv4 only please try { await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false); return(new NetworkStream(socket, true)); } catch (Exception) { socket.Dispose(); throw; } } }; HttpClient = new HttpClient(handler); HttpClient.DefaultRequestHeaders .TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (GTAServer.core " + GetServerVersion() + ")"); }
private static HttpMessageHandler ValueFactory(HttpHandlerOptions handlerOptions) { var socketsHandler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.FromSeconds(60), PooledConnectionIdleTimeout = TimeSpan.FromMinutes(20), MaxConnectionsPerServer = 2 }; if (handlerOptions.Proxy != null) { socketsHandler.Proxy = handlerOptions.Proxy; } if (handlerOptions.IgnoreProxy) { socketsHandler.UseProxy = false; } if (handlerOptions.ClientCertificates != null) { foreach (var handlerOptionsClientCertificate in handlerOptions.ClientCertificates) { if (socketsHandler.SslOptions.ClientCertificates == null) { socketsHandler.SslOptions.ClientCertificates = new X509CertificateCollection(); } socketsHandler.SslOptions.ClientCertificates.Add(handlerOptionsClientCertificate); } } return(socketsHandler); }
private static HttpClient CreateHttpClient(Uri baseAddress, bool automaticDecompression, IWebProxy proxy) { #if NET5_0_OR_GREATER var handler = new SocketsHttpHandler(); #else var handler = new HttpClientHandler(); #endif if (proxy != null) { handler.Proxy = proxy; handler.UseProxy = true; } if (automaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("User-Agent", UserAgent); client.BaseAddress = baseAddress; return(client); }
public Client(string baseUrl, ILogger <Client> logger) { var socketsHandler = new SocketsHttpHandler { PooledConnectionLifetime = TimeSpan.Zero, PooledConnectionIdleTimeout = TimeSpan.Zero, ConnectCallback = async(ctx, cancellationToken) => { var socket = new Socket(SocketType.Stream, ProtocolType.Tcp); socket.NoDelay = true; socket.UseOnlyOverlappedIO = true; await socket.ConnectAsync(ctx.DnsEndPoint); var networkStream = new NetworkStream(socket, true); return(networkStream); }, }; _httpClient = new HttpClient(socketsHandler); _httpClient.DefaultRequestHeaders.Add("Accept", "application/json"); _httpClient.DefaultRequestVersion = HttpVersion.Version10; _httpClient.DefaultVersionPolicy = HttpVersionPolicy.RequestVersionExact; _baseUrl = baseUrl; _logger = logger; }
private static HttpMessageInvoker CreateInternalHttpInvoker(HttpMessageHandler?handler) { // HttpMessageInvoker should always dispose handler if Disposed is called on it. // Decision to dispose invoker is controlled by _shouldDisposeHttpClient. if (handler == null) { #if NET5_0 handler = new SocketsHttpHandler { EnableMultipleHttp2Connections = true }; #else handler = new HttpClientHandler(); #endif } #if NET5_0 // HttpClientHandler has an internal handler that sets request telemetry header. // If the handler is SocketsHttpHandler then we know that the header will never be set // so wrap with a telemetry header setting handler. if (IsSocketsHttpHandler(handler)) { handler = new TelemetryHeaderHandler(handler); } #endif var httpInvoker = new HttpMessageInvoker(handler, disposeHandler: true); return(httpInvoker); }
private void Init() { var sockets = new SocketsHttpHandler() { PooledConnectionLifetime = TimeSpan.FromMinutes(10), PooledConnectionIdleTimeout = TimeSpan.FromMinutes(5), MaxConnectionsPerServer = 10, UseCookies = true }; //var url = "https://www.ximalaya.com/xiqu/6113767/"; var http = new HttpClient(sockets); //http.DefaultRequestHeaders.Host = "www.ximalaya.com/"; http.DefaultRequestHeaders.Referrer = new Uri("https://www.ximalaya.com/"); http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Chrome", "78.0.3904.87")); http.BaseAddress = new Uri("https://www.ximalaya.com"); xmlyClicnt = http; _downloadClient = new HttpClient(sockets); //_downloadClient.DefaultRequestHeaders.Host = "www.ximalaya.com/"; _downloadClient.DefaultRequestHeaders.Referrer = new Uri("https://www.ximalaya.com/"); _downloadClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Chrome", "78.0.3904.87")); }
protected virtual System.Net.Http.HttpClient CreateHttpClient(HttpProxySettings proxySettings) { var handler = new SocketsHttpHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Brotli, UseCookies = false, // sic - we don't want to use a shared cookie container AllowAutoRedirect = false, Credentials = GetCredentialCache(), PreAuthenticate = true, MaxConnectionsPerServer = 12, ConnectCallback = onConnect, SslOptions = new SslClientAuthenticationOptions { RemoteCertificateValidationCallback = _certificateValidationService.ShouldByPassValidationError } }; if (proxySettings != null) { handler.Proxy = _createManagedWebProxy.GetWebProxy(proxySettings); } var client = new System.Net.Http.HttpClient(handler) { Timeout = Timeout.InfiniteTimeSpan }; return(client); }
/// <summary> /// HttpClient with SocketsHttpHandler, ArmTransientErrorHandler and ArmErrorHandler. /// With ClientId/ClientCertificate based authorization. /// Accepts json with optional GZip. /// </summary> public static ArmClient Connect() { var accessToken = AccessTokenProvider .FromClientIdAndClientCertificate(AzureResourceManagerScope) .ConfigureAwait(false) .GetAwaiter() .GetResult(); var authHeader = new AuthenticationHeaderValue("Bearer", accessToken); HttpMessageHandler handler = new SocketsHttpHandler() { AutomaticDecompression = DecompressionMethods.GZip, }; handler = new ArmTransientErrorHandler(handler); handler = new ArmErrorHandler(handler); var client = new ArmClient(handler); client.BaseAddress = new Uri(AzureResourceManagerBaseUri); client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = authHeader; return(client); }
private void SetServerSslSecurity(IHttpRequest request, SocketsHttpHandler socketsHttpHandler) { // Until .NET Core 2.0 this was HttpClientHandler. Starting from .NET Core 2.1 this is SocketsHttpHandler if (request.Options.AllowInsecureSslServer && request.UsesSsl()) { // Until .NET Core 2.0: clientHandler.ServerCertificateCustomValidationCallback += delegate(HttpRequestMessage sender, X509Certificate2 cert, X509Chain chain, SslPolicyErrors error) // Starting from .NET Core 2.1: socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback += delegate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (string.IsNullOrEmpty(cert.GetCertHashString())) { return(false); } var sslThumbprint = cert.GetCertHashString().ToLowerInvariant(); var configThumbprint = this.config.SslCertThumbprint.ToLowerInvariant(); if (sslThumbprint == configThumbprint) { return(true); } this.log.LogError("The remote endpoint is using an unknown/invalid SSL certificate, " + "the thumbprint of the certificate doesn't match the value in the configuration", new { sslThumbprint, configThumbprint }); return(false); }; } }
public async Task Expect100Continue_WaitsExpectedPeriodOfTimeBeforeSendingContent() { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var handler = new SocketsHttpHandler()) using (var invoker = new HttpMessageInvoker(handler)) { TimeSpan delay = TimeSpan.FromSeconds(3); handler.Expect100ContinueTimeout = delay; var tcs = new TaskCompletionSource <bool>(); var content = new SetTcsContent(new MemoryStream(new byte[1]), tcs); var request = new HttpRequestMessage(HttpMethod.Post, uri) { Content = content, Version = UseVersion }; request.Headers.ExpectContinue = true; long start = Environment.TickCount64; (await invoker.SendAsync(TestAsync, request, default)).Dispose(); long elapsed = content.Ticks - start; Assert.True(elapsed >= delay.TotalMilliseconds); } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAsync(); await connection.ReadAsync(new byte[1], 0, 1); await connection.SendResponseAsync(); }); }); }
public void Configure(HostBuilderContext context, IServiceCollection services) { services.AddCodeFirstGrpcClient <IGrpcService>(o => { var handler = new SocketsHttpHandler { PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan, KeepAlivePingDelay = TimeSpan.FromSeconds(60), // This keeps the connection open at all times by pinging every 60s KeepAlivePingTimeout = TimeSpan.FromSeconds(30), EnableMultipleHttp2Connections = true, }; o.Address = new Uri("https://localhost:22377"); o.ChannelOptionsActions.Add(o => { o.HttpClient = null; o.HttpHandler = handler; }); }); services.AddSingleton <IGetClientProcessInfoService, GetClientProcessInfoService>(); services.AddSingleton <IClientQueuedRequests, ClientQueuedRequests>(); services.AddSingleton <IClientQueuedResponses, ClientQueuedResponses>(); services.AddSingleton <IClientRequestProcessor, ClientRequestProcessor>(); services.AddSingleton <IClientResponseMetaDataFactory, ClientResponseMetaDataFactory>(); }
/// <summary> /// Allows configuring the <see cref="SocketsHttpHandler"/> instance. The base implementation /// applies settings from <see cref="ForwarderHttpClientContext.NewConfig"/>. /// <see cref="SocketsHttpHandler.UseProxy"/>, <see cref="SocketsHttpHandler.AllowAutoRedirect"/>, /// <see cref="SocketsHttpHandler.AutomaticDecompression"/>, and <see cref="SocketsHttpHandler.UseCookies"/> /// are disabled prior to this call. /// </summary> protected virtual void ConfigureHandler(ForwarderHttpClientContext context, SocketsHttpHandler handler) { var newConfig = context.NewConfig; if (newConfig.SslProtocols.HasValue) { handler.SslOptions.EnabledSslProtocols = newConfig.SslProtocols.Value; } if (newConfig.MaxConnectionsPerServer is not null) { handler.MaxConnectionsPerServer = newConfig.MaxConnectionsPerServer.Value; } if (newConfig.DangerousAcceptAnyServerCertificate ?? false) { handler.SslOptions.RemoteCertificateValidationCallback = delegate { return(true); }; } #if NET handler.EnableMultipleHttp2Connections = newConfig.EnableMultipleHttp2Connections.GetValueOrDefault(true); if (newConfig.RequestHeaderEncoding is not null) { var encoding = Encoding.GetEncoding(newConfig.RequestHeaderEncoding); handler.RequestHeaderEncodingSelector = (_, _) => encoding; } #endif var webProxy = TryCreateWebProxy(newConfig.WebProxy); if (webProxy is not null) { handler.Proxy = webProxy; handler.UseProxy = true; } }
public static HttpMessageInvoker CreateClient(TimeSpan?idleTimeout = null, TimeSpan?expect100ContinueTimeout = null, bool includeClientCert = false) { var handler = new SocketsHttpHandler(); handler.SslOptions = new System.Net.Security.SslClientAuthenticationOptions { RemoteCertificateValidationCallback = (_, __, ___, ____) => true, TargetHost = "targethost", ClientCertificates = !includeClientCert ? null : new X509CertificateCollection() { TestResources.GetTestCertificate() }, }; if (expect100ContinueTimeout != null) { handler.Expect100ContinueTimeout = expect100ContinueTimeout.Value; } if (idleTimeout != null) { handler.PooledConnectionIdleTimeout = idleTimeout.Value; } return(new HttpMessageInvoker(handler)); }
public GossipController(IPublisher publisher, IPublisher networkSendQueue, TimeSpan gossipTimeout, Func <X509Certificate, X509Chain, SslPolicyErrors, ValueTuple <bool, string> > serverCertValidator, X509Certificate clientCertificate) : base(publisher) { _networkSendQueue = networkSendQueue; _gossipTimeout = gossipTimeout; var socketsHttpHandler = new SocketsHttpHandler { SslOptions = { RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => { var(isValid, error) = serverCertValidator(certificate, chain, errors); if (!isValid && error != null) { Log.Error("Server certificate validation error: {e}", error); } return(isValid); }, ClientCertificates = new X509CertificateCollection() } }; if (clientCertificate != null) { socketsHttpHandler.SslOptions.ClientCertificates.Add(clientCertificate); } _client = new HttpAsyncClient(_gossipTimeout, socketsHttpHandler); }
public StandardHttpMessageHandler(HttpContext httpContext, ILogger logger) { _httpContext = httpContext; _logger = logger; InnerHandler = new SocketsHttpHandler(); }