How to use HttpClientHandler with HttpClientFactory in .NET Core

More properly to define primary HttpMessageHandler via ConfigurePrimaryHttpMessageHandler() method of HttpClientBuilder. See example below to configure typed client how. services.AddHttpClient<TypedClient>() .ConfigureHttpClient((sp, httpClient) => { var options = sp.GetRequiredService<IOptions<SomeOptions>>().Value; httpClient.BaseAddress = options.Url; httpClient.Timeout = options.RequestTimeout; }) .SetHandlerLifetime(TimeSpan.FromMinutes(5)) .ConfigurePrimaryHttpMessageHandler(x => new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; }) .AddHttpMessageHandler(sp => sp.GetService<SomeCustomHandler>().CreateAuthHandler()) .AddPolicyHandlerFromRegistry(PollyPolicyName.HttpRetry) .AddPolicyHandlerFromRegistry(PollyPolicyName.HttpCircuitBreaker); Also you can … Read more

Web Api + HttpClient: An asynchronous module or handler completed while an asynchronous operation was still pending

Your problem is a subtle one: the async lambda you’re passing to PushStreamContent is being interpreted as an async void (because the PushStreamContent constructor only takes Actions as parameters). So there’s a race condition between your module/handler completing and the completion of that async void lambda. PostStreamContent detects the stream closing and treats that as … Read more

Pass multiple complex objects to a post/put Web API method

In the current version of Web API, the usage of multiple complex objects (like your Content and Config complex objects) within the Web API method signature is not allowed. I’m betting good money that config (your second parameter) is always coming back as NULL. This is because only one complex object can be parsed from … Read more

Should I share types between a Web API service and its client ? What are the other options?

I would argue that if you are not careful, the second option could end up being less RESTful than the first. REST is less about de-coupling and more about managing and focusing the coupling between client and server. In a restful system you know the coupling between client and server lies in the media type … Read more

How to pass in a mocked HttpClient in a .NET test?

You can replace the core HttpMessageHandler with a fake one. Something that looks like this… public class FakeResponseHandler : DelegatingHandler { private readonly Dictionary<Uri, HttpResponseMessage> _FakeResponses = new Dictionary<Uri, HttpResponseMessage>(); public void AddFakeResponse(Uri uri, HttpResponseMessage responseMessage) { _FakeResponses.Add(uri, responseMessage); } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { if (_FakeResponses.ContainsKey(request.RequestUri)) { return Task.FromResult(_FakeResponses[request.RequestUri]); } else … Read more

Re-using HttpClient but with a different Timeout setting per request?

Under the hood, HttpClient just uses a cancellation token to implement the timeout behavior. You can do the same directly if you want to vary it per request: using var cts = new CancellationTokenSource(); cts.CancelAfter(TimeSpan.FromSeconds(30)); await httpClient.GetAsync(“http://www.google.com”, cts.Token); Note that the default timeout for HttpClient is 100 seconds, and the request will still be canceled … Read more

How do you use Basic Authentication with System.Net.Http.HttpClient?

It looks like you can’t use PostAsync and have access to mess with the Headers for authentication. I had to use an HttpRequestMessage and SendAsync. //setup reusable http client HttpClient client = new HttpClient(); Uri baseUri = new Uri(url); client.BaseAddress = baseUri; client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.ConnectionClose = true; //Post body content var values = new List<KeyValuePair<string, string>>(); … Read more