gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:19:23 24 4
gpt4 key购买 nike

我有代码将命名的 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 的私有(private)字段中。你可以得到它,但它有点非正统。所以,你可能感兴趣也可能不感兴趣,但我会把它扔在那里,以防你:

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.");
}

关于c# - 验证我的 DelegatingHandler 是否已添加到 IHttpClientBuilder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63678810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com