/// <summary> /// Reusing a single HttpClient instance across a multi-threaded application /// </summary> public HttpClient GetOrCreate( Uri baseAddress, IDictionary <string, string>?defaultRequestHeaders = null, TimeSpan?timeout = null, long?maxResponseContentBufferSize = null, HttpMessageHandler?handler = null) { return(_httpClients.GetOrAdd(baseAddress, uri => new Lazy <HttpClient>(() => { // Reusing a single HttpClient instance across a multi-threaded application means // you can't change the values of the stateful properties (which are not thread safe), // like BaseAddress, DefaultRequestHeaders, MaxResponseContentBufferSize and Timeout. // So you can only use them if they are constant across your application and need their own instance if being varied. var client = handler == null ? new HttpClient { BaseAddress = baseAddress } : new HttpClient(handler, disposeHandler: false) { BaseAddress = baseAddress }; setRequestTimeout(timeout, client); setMaxResponseBufferSize(maxResponseContentBufferSize, client); setDefaultHeaders(defaultRequestHeaders, client); setConnectionLeaseTimeout(baseAddress, client); return client; }, LazyThreadSafetyMode.ExecutionAndPublication)).Value); }
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); }
public NetHttpClient(IProxyConfig proxyConfig) { Ensure.ArgumentNotNull(proxyConfig, nameof(proxyConfig)); _httpMessageHandler = CreateMessageHandler(proxyConfig); _httpClient = new HttpClient(_httpMessageHandler); }
private void EnsureServer() { if (_host == null) { var builder = new HostBuilder() .ConfigureServices(services => { services.AddSingleton <ILoggerFactory>(LoggerFactory); // Registers a service for tests to add new methods services.AddSingleton <DynamicGrpcServiceRegistry>(); }) .ConfigureWebHostDefaults(webHost => { webHost .UseTestServer() .UseStartup <TStartup>(); _configureWebHost?.Invoke(webHost); }); _host = builder.Start(); _server = _host.GetTestServer(); _handler = _server.CreateHandler(); _dynamicGrpc = _server.Services.GetRequiredService <DynamicGrpcServiceRegistry>(); } }
public Aria2Connection(Uri baseUri, string token, HttpMessageHandler?handler = null, bool shutdownOnDisposal = true) { _httpClient = handler is null ? new HttpClient() : new HttpClient(handler); _httpClient.BaseAddress = baseUri; _tokenParam = "token:" + token; _shutdownOnDisposal = shutdownOnDisposal; }
internal WebServiceClient( int accountId, string licenseKey, IEnumerable <string>?locales, string host, int timeout, HttpMessageHandler?httpMessageHandler, // This is a hack so that we can keep this internal while adding // httpMessageHandler to the public constructor. We can remove // this when we drop .NET 4.5 support and get rid of ISyncClient. bool fakeParam = false #if !NETSTANDARD1_4 , ISyncClient?syncWebRequest = null #endif , HttpClient?httpClient = null ) { var auth = EncodedAuth(accountId, licenseKey); _host = host; _locales = locales == null ? new List <string> { "en" } : new List <string>(locales); #if !NETSTANDARD1_4 _syncClient = syncWebRequest ?? new SyncClient(auth, timeout, UserAgent); #endif _asyncClient = new AsyncClient(auth, timeout, UserAgent, httpMessageHandler, httpClient); }
public AsyncClient( string auth, int timeout, ProductInfoHeaderValue userAgent, HttpMessageHandler?httpMessageHandler = null, HttpClient?httpClient = null ) { if (httpClient == null) { _httpMessageHandler = httpMessageHandler ?? new HttpClientHandler(); try { _httpClient = new HttpClient(_httpMessageHandler); } catch { _httpClient?.Dispose(); _httpMessageHandler.Dispose(); throw; } } else { _httpClient = httpClient; } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.UserAgent.Add(userAgent); _httpClient.Timeout = TimeSpan.FromMilliseconds(timeout); }
/// <summary> /// Adds a Refit client to the DI container /// </summary> /// <typeparam name="T">Type of the Refit interface</typeparam> /// <param name="services">container</param> /// <param name="settings">Optional. Settings to configure the instance with</param> /// <returns></returns> public static IHttpClientBuilder AddRefitClient <T>(this IServiceCollection services, RefitSettings?settings = null) where T : class { services.AddSingleton(provider => RequestBuilder.ForType <T>(settings)); return(services.AddHttpClient(UniqueName.ForType <T>()) .ConfigureHttpMessageHandlerBuilder(builder => { // check to see if user provided custom auth token HttpMessageHandler?innerHandler = null; if (settings != null) { if (settings.HttpMessageHandlerFactory != null) { innerHandler = settings.HttpMessageHandlerFactory(); } if (settings.AuthorizationHeaderValueGetter != null) { innerHandler = new AuthenticatedHttpClientHandler(settings.AuthorizationHeaderValueGetter, innerHandler); } else if (settings.AuthorizationHeaderValueWithParamGetter != null) { innerHandler = new AuthenticatedParameterizedHttpClientHandler(settings.AuthorizationHeaderValueWithParamGetter, innerHandler); } } if (innerHandler != null) { builder.PrimaryHandler = innerHandler; } }) .AddTypedClient((client, serviceProvider) => RestService.For <T>(client, serviceProvider.GetService <IRequestBuilder <T> >() !))); }
public ClusterEndpointDiscoverer( int maxDiscoverAttempts, EndPoint[] gossipSeeds, TimeSpan gossipTimeout, bool gossipOverHttps, TimeSpan discoveryInterval, NodePreference nodePreference, HttpMessageHandler?httpMessageHandler = null) { _maxDiscoverAttempts = maxDiscoverAttempts; _gossipSeeds = gossipSeeds; _discoveryInterval = discoveryInterval; _nodePreference = nodePreference; _gossipClients = new Dictionary <EndPoint, GossipClient>(); _gossipClientFactory = gossipSeedEndPoint => { string url = gossipSeedEndPoint.ToHttpUrl(gossipOverHttps?EndPointExtensions.HTTPS_SCHEMA:EndPointExtensions.HTTP_SCHEMA); var httpHandler = httpMessageHandler ?? new HttpClientHandler(); #if NETSTANDARD2_1 httpHandler = new DefaultRequestVersionHandler(httpHandler); #endif var channel = GrpcChannel.ForAddress(url, new GrpcChannelOptions { HttpClient = new HttpClient(httpHandler) { Timeout = gossipTimeout, #if NETCOREAPP3_1 DefaultRequestVersion = new Version(2, 0), #endif } }); var callInvoker = channel.CreateCallInvoker(); return(new GossipClient(callInvoker)); }; }
/// <summary> /// Adds a Refit client to the DI container /// </summary> /// <param name="services">container</param> /// <param name="refitInterfaceType">Type of the Refit interface</param> /// <param name="settings">Optional. Settings to configure the instance with</param> /// <returns></returns> public static IHttpClientBuilder AddRefitClient(this IServiceCollection services, Type refitInterfaceType, RefitSettings?settings = null) { return(services.AddHttpClient(UniqueName.ForType(refitInterfaceType)) .ConfigureHttpMessageHandlerBuilder(builder => { // check to see if user provided custom auth token HttpMessageHandler?innerHandler = null; if (settings != null) { if (settings.HttpMessageHandlerFactory != null) { innerHandler = settings.HttpMessageHandlerFactory(); } if (settings.AuthorizationHeaderValueGetter != null) { innerHandler = new AuthenticatedHttpClientHandler(settings.AuthorizationHeaderValueGetter, innerHandler); } else if (settings.AuthorizationHeaderValueWithParamGetter != null) { innerHandler = new AuthenticatedParameterizedHttpClientHandler(settings.AuthorizationHeaderValueWithParamGetter, innerHandler); } } if (innerHandler != null) { builder.PrimaryHandler = innerHandler; } }) .AddTypedClient(refitInterfaceType, (client, serviceProvider) => RestService.For(refitInterfaceType, client, settings))); }
public void CreateClient_NoPrimaryHandlerNet5OrLater_SocketsHttpHandlerConfigured() { // Arrange var services = new ServiceCollection(); services .AddGrpcClient <TestGreeterClient>(o => o.Address = new Uri("https://localhost")); var serviceProvider = services.BuildServiceProvider(validateScopes: true); var clientFactory = CreateGrpcClientFactory(serviceProvider); // Act var handlerFactory = serviceProvider.GetRequiredService <IHttpMessageHandlerFactory>(); var handler = handlerFactory.CreateHandler(nameof(TestGreeterClient)); // Assert var hasSocketsHttpHandler = false; HttpMessageHandler?currentHandler = handler; while (currentHandler is DelegatingHandler delegatingHandler) { currentHandler = delegatingHandler.InnerHandler; if (currentHandler?.GetType() == typeof(SocketsHttpHandler)) { hasSocketsHttpHandler = true; break; } } Assert.IsTrue(hasSocketsHttpHandler); }
public AsyncClient( string auth, int timeout, ProductInfoHeaderValue userAgent, HttpMessageHandler?httpMessageHandler = null ) { _httpMessageHandler = httpMessageHandler ?? new HttpClientHandler(); try { _httpClient = new HttpClient(_httpMessageHandler) { DefaultRequestHeaders = { Authorization = new AuthenticationHeaderValue("Basic", auth), Accept = { new MediaTypeWithQualityHeaderValue("application/json") }, UserAgent = { userAgent } }, Timeout = TimeSpan.FromMilliseconds(timeout) }; } catch { _httpClient?.Dispose(); _httpMessageHandler.Dispose(); throw; } }
private async Task TestTelemetryHeaderIsSet(ClientType clientType, HttpMessageHandler?handler) { string?telemetryHeader = null; Task <HelloReply> UnaryTelemetryHeader(HelloRequest request, ServerCallContext context) { telemetryHeader = context.RequestHeaders.GetValue( #if NET5_0 "traceparent" #else "request-id" #endif ); return(Task.FromResult(new HelloReply())); } // Arrange var method = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>(UnaryTelemetryHeader); var client = CreateClient(clientType, method, handler); // Act await client.UnaryCall(new HelloRequest()); // Assert Assert.IsNotNull(telemetryHeader); }
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. var httpInvoker = new HttpMessageInvoker(handler ?? new HttpClientHandler(), disposeHandler: true); return(httpInvoker); }
/// <summary> /// Creates an <see cref="HttpClient"/> that uses the interceptors registered for the current instance. /// </summary> /// <param name="innerHandler">The optional inner <see cref="HttpMessageHandler"/>.</param> /// <returns> /// The <see cref="HttpClient"/> that uses the current <see cref="HttpClientInterceptorOptions"/>. /// </returns> public virtual HttpClient CreateHttpClient(HttpMessageHandler?innerHandler = null) { #pragma warning disable CA2000 var handler = new InterceptingHttpMessageHandler(this, innerHandler ?? new HttpClientHandler()); #pragma warning restore CA2000 return(new HttpClient(handler, true)); }
public Client( Uri serviceUri, HttpMessageHandler?handler = null, ILogger <Client>?logger = null) { _serviceUri = serviceUri; _logger = logger ?? NullLogger <Client> .Instance; _client = new HttpClient(handler ?? new HttpClientHandler()); }
/// <summary> /// Initializes a new instance of the <see cref="WebServiceClient" /> class. /// </summary> /// <param name="accountId">Your MaxMind account ID.</param> /// <param name="licenseKey">Your MaxMind license key.</param> /// <param name="locales">List of locale codes to use in name property from most preferred to least preferred.</param> /// <param name="host">The host to use when accessing the service</param> /// <param name="timeout">Timeout in milliseconds for connection to web service. The default is 3000.</param> /// <param name="httpMessageHandler">The <c>HttpMessageHandler</c> to use when creating the <c>HttpClient</c>.</param> public WebServiceClient( int accountId, string licenseKey, IEnumerable <string>?locales = null, string host = "geoip.maxmind.com", int timeout = 3000, HttpMessageHandler?httpMessageHandler = null ) : this(accountId, licenseKey, locales, host, timeout, null, false) { }
public SeqIngestionApiClient(string serverUrl, string?apiKey, HttpMessageHandler?messageHandler) { if (serverUrl == null) { throw new ArgumentNullException(nameof(serverUrl)); } _apiKey = apiKey; _httpClient = messageHandler != null ? new HttpClient(messageHandler) : new HttpClient(); _httpClient.BaseAddress = new Uri(NormalizeServerBaseAddress(serverUrl)); }
public JwkRsaProviderService( JwtAuthorization jwtAuthorizationConfiguration, HttpMessageHandler?httpMessageHandler = null) { httpMessageHandler ??= new HttpClientHandler(); _httpClient = new HttpClient(httpMessageHandler); _httpClient.DefaultRequestHeaders.Add("accept", "application/json"); _jwkUrl = new Uri(jwtAuthorizationConfiguration.JwkUrl); }
public FluentMiddlewareHttpHandler( IFluentHttpMiddlewareRunner middlewareRunner, FluentHttpClient httpClient, RequestTracker requestTracker, HttpMessageHandler?messageHandler = null ) : base(messageHandler ?? new HttpClientHandler()) { _middlewareRunner = middlewareRunner; _httpClient = httpClient; _requestTracker = requestTracker; }
public DigitalstromConnectionProvider(UriPriorityList uris, IDigitalstromAuth authData, X509Certificate2?cert = null, Func <X509Certificate2, bool>?certCallback = null, HttpMessageHandler?handler = null) { Uris = uris; AuthData = authData; ServerCertificate = cert; ServerCertificateValidationCallback = certCallback; if (handler != null) { Handler = handler; } }
public static ClusterAwareHttpHandler Create(EventStoreClientSettings settings, HttpMessageHandler?httpMessageHandler = null) => new ClusterAwareHttpHandler( settings.ConnectivitySettings.NodePreference == NodePreference.Leader, new ClusterEndpointDiscoverer( settings.ConnectivitySettings.MaxDiscoverAttempts, settings.ConnectivitySettings.GossipSeeds, settings.ConnectivitySettings.GossipTimeout, settings.ConnectivitySettings.DiscoveryInterval, settings.ConnectivitySettings.NodePreference, httpMessageHandler)) { InnerHandler = httpMessageHandler };
private static AuditTrailClient CreateClient(HttpMessageHandler handler, HttpMessageHandler?tokenHandler = null, bool tokenSinkResult = true, IAuditTrailStore?store = null, IHostEnvironment?env = null) { var options = new AuditTrailClientOptions { DeliveryEndpoint = "https://uruk.example.com/events" }; HttpClient httpClient = new HttpClient(handler); return(new AuditTrailClient( httpClient, Options.Create(options), new TestTokenSink(tokenSinkResult), store ?? new TestTokenStore(), new TestLogger <AuditTrailClient>(), new NullAccessTokenAcquisitor(), env)); }
public ClusterEndpointDiscoverer( int maxDiscoverAttempts, EndPoint[] gossipSeeds, TimeSpan gossipTimeout, TimeSpan discoveryInterval, NodePreference nodePreference, HttpMessageHandler?httpMessageHandler = null) { _maxDiscoverAttempts = maxDiscoverAttempts; _gossipSeeds = gossipSeeds; _discoveryInterval = discoveryInterval; _client = new HttpClient(httpMessageHandler ?? new HttpClientHandler()) { Timeout = gossipTimeout }; _nodePreference = nodePreference; }
private async Task TestTelemetryHeaderIsSet(ClientType clientType, HttpMessageHandler?handler) { string?telemetryHeader = null; Task <HelloReply> UnaryTelemetryHeader(HelloRequest request, ServerCallContext context) { telemetryHeader = context.RequestHeaders.GetValue( #if NET5_0_OR_GREATER "traceparent" #else "request-id" #endif ); return(Task.FromResult(new HelloReply())); } // Arrange var method = Fixture.DynamicGrpc.AddUnaryMethod <HelloRequest, HelloReply>(UnaryTelemetryHeader); var client = CreateClient(clientType, method, handler); // Act #if NET5_0_OR_GREATER var result = new List <KeyValuePair <string, object?> >(); using var allSubscription = new AllListenersObserver(new Dictionary <string, IObserver <KeyValuePair <string, object?> > > { ["HttpHandlerDiagnosticListener"] = new ObserverToList <KeyValuePair <string, object?> >(result) }); using (DiagnosticListener.AllListeners.Subscribe(allSubscription)) #endif { await client.UnaryCall(new HelloRequest()).ResponseAsync.DefaultTimeout(); } // Assert Assert.IsNotNull(telemetryHeader); #if NET5_0_OR_GREATER Assert.AreEqual(4, result.Count); Assert.AreEqual("System.Net.Http.HttpRequestOut.Start", result[0].Key); Assert.AreEqual("System.Net.Http.Request", result[1].Key); Assert.AreEqual("System.Net.Http.HttpRequestOut.Stop", result[2].Key); Assert.AreEqual("System.Net.Http.Response", result[3].Key); #endif }
public DurableSeqSink( string serverUrl, string bufferBaseFilename, string?apiKey, int batchPostingLimit, TimeSpan period, long?bufferSizeLimitBytes, long?eventBodyLimitBytes, ControlledLevelSwitch controlledSwitch, HttpMessageHandler?messageHandler, long?retainedInvalidPayloadsLimitBytes) { if (serverUrl == null) { throw new ArgumentNullException(nameof(serverUrl)); } if (bufferBaseFilename == null) { throw new ArgumentNullException(nameof(bufferBaseFilename)); } var fileSet = new FileSet(bufferBaseFilename); _shipper = new HttpLogShipper( fileSet, new SeqIngestionApiClient(serverUrl, apiKey, messageHandler), batchPostingLimit, period, eventBodyLimitBytes, controlledSwitch, retainedInvalidPayloadsLimitBytes, bufferSizeLimitBytes); const long individualFileSizeLimitBytes = 100L * 1024 * 1024; _sink = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.File(new ConstrainedBufferedFormatter(eventBodyLimitBytes), fileSet.RollingFilePathFormat, rollingInterval: RollingInterval.Day, fileSizeLimitBytes: individualFileSizeLimitBytes, rollOnFileSizeLimit: true, retainedFileCountLimit: null, encoding: Encoding.UTF8) .CreateLogger(); }
public ServerClient(HttpMessageHandler?handler = null) { _connection = new HubConnectionBuilder() .WithUrl(Url, o => { if (handler != null) { o.HttpMessageHandlerFactory = _ => handler; } }) //.AddMessagePackProtocol() .AddNewtonsoftJsonProtocol() .WithAutomaticReconnect() .Build(); _httpClient = new HttpClient(); _httpClient.BaseAddress = new Uri(Url, UriKind.RelativeOrAbsolute); }
/// <summary> /// Set options from the specified options config. /// </summary> /// <param name="options"></param> /// <returns></returns> public FluentHttpClientBuilder FromOptions(FluentHttpClientOptions options) { _timeout = options.Timeout; _baseUrl = options.BaseUrl; Identifier = options.Identifier; WithHeaders(options.Headers); _middlewareBuilder.AddRange(options.MiddlewareBuilder.GetAll()); _requestBuilderDefaults = options.RequestBuilderDefaults; _httpMessageHandler = options.HttpMessageHandler; var formatters = options.Formatters.Union(_formatterOptions.Formatters, MediaTypeFormatterComparer.Instance).ToList(); _formatterOptions.Formatters.Clear(); _formatterOptions.Formatters.AddRange(formatters); _formatterOptions.Default = options.DefaultFormatter; return(this); }
////private EnsureDbHostedService? _ensureDb; private void EnsureServer() { if (_host == null) { var builder = new HostBuilder() .ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Information); }) .ConfigureServices(services => { //services.AddSingleton<ILoggerFactory>(LoggerFactory); }) .ConfigureWebHostDefaults(builder => { builder.UseTestServer(); if (Configuration == null) { builder.UseStartup <Startup>(); } else { builder.UseStartup <Startup>(context => new Startup(Configuration)); } builder.ConfigureTestServices(services => { ////services.AddHostedService<EnsureDbHostedService>(services => ////{ //// var logger = services.GetRequiredService<ILogger<EnsureDbHostedService>>(); //// _ensureDb = new EnsureDbHostedService(logger, services); //// return _ensureDb; ////}); }); _configureWebHost?.Invoke(builder); }) .UseNLog(); _host = builder.Start(); _server = _host.GetTestServer(); _handler = _server.CreateHandler(); } }
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) { handler = HttpHandlerFactory.CreatePrimaryHandler(); } #if NET5_0 handler = HttpHandlerFactory.EnsureTelemetryHandler(handler); #endif // Use HttpMessageInvoker instead of HttpClient because it is faster // and we don't need client's features. var httpInvoker = new HttpMessageInvoker(handler, disposeHandler: true); return(httpInvoker); }