.NET by Patrik

The Solution: Using Reflection to Inspect HttpClient Handlers

To test HttpClient handlers effectively, you need to inspect the internal handler chain that .NET builds at runtime. Since this chain is stored in a private field, reflection is the only reliable method to access it. The approach is safe, does not modify production code, and gives you full visibility into the pipeline.

The process begins by resolving your service from the DI container. If your service stores the HttpClient in a protected field, you can access it using reflection:

var field = typeof(MyClient)
    .GetField("_httpClient", BindingFlags.Instance | BindingFlags.NonPublic);

var httpClient = (HttpClient)field.GetValue(serviceInstance);

Next, retrieve the private _handler field from HttpMessageInvoker:

var handlerField = typeof(HttpMessageInvoker)
    .GetField("_handler", BindingFlags.Instance | BindingFlags.NonPublic);

var current = handlerField.GetValue(httpClient);

Finally, walk through the entire handler chain:

var handlers = new List<DelegatingHandler>();

while (current is DelegatingHandler delegating)
{
    handlers.Add(delegating);
    current = delegating.InnerHandler;
}

With this list, you can assert the presence of your custom handlers:

Assert.Contains(handlers, h => h is HttpRetryHandler);
Assert.Contains(handlers, h => h is HttpLogHandler);

This gives your test real confidence that the HttpClient pipeline is constructed correctly—exactly as it will run in production.

reflection
csharp
testing
httpclient
pipeline

Comments