验证我的 DelegatingHandler 是否已添加到 IHttpClientBuilder

Verify that my DelegatingHandler was added to IHttpClientBuilder

我有代码将命名的 HttpClient 添加到 ServiceCollection 并将 DelegatingHandler 添加到客户端。示例代码:

public class MyDelegatingHandler : DelegatingHandler
{
    // ...
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHttpClient("MyClient")
                .AddHttpMessageHandler(provider => new MyDelegatingHandler());
        });

编写单元测试时,如何验证添加的 DelegatingHandler 实现是 MyDelegatingHanlder

此信息存储在 HttpClient 的私有字段中。你可以得到它,但它有点非正统。所以,你可能感兴趣也可能不感兴趣,但我会把它扔在那里,以防你:

public static class HttpClientExtensions
{
    public static bool ContainsDelegatingHandler<TDelegatingHandler>(
        this HttpClient httpClient) where TDelegatingHandler: DelegatingHandler
    {
        if(httpClient == null)
        {
            throw new ArgumentNullException(nameof(httpClient));
        }

        var internalHandlerField = typeof(HttpMessageInvoker).GetField(
            "_handler", BindingFlags.NonPublic | BindingFlags.Instance);
        if(internalHandlerField == null)
        {
            throw new InvalidOperationException(
                "_handler no longer exists as a private instance field of HttpClient");
        }

        // run down the chain of delegating handlers until there are no more
        var delegatingHandler = internalHandlerField.GetValue(httpClient) as DelegatingHandler;
        while (delegatingHandler != null)
        {
            if(delegatingHandler.GetType() == typeof(TDelegatingHandler))
            {
                return true;
            }
            delegatingHandler = delegatingHandler.InnerHandler as DelegatingHandler;
        }

        return false;
    }
}

要进行测试,您首先必须使用工厂创建一个 HttpClient

var httpClient = httpClientFactory.CreateClient("MyClient");

然后运行它通过扩展:

if(!httpClient.ContainsDelegatingHandler<MyDelegatingHandler>())
{
    throw new Exception(
        "HttpClient with name 'MyClient' does not contain " +
        $"{nameof(MyDelegatingHandler)} delegating handler.");
}