此信息存储在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.");
}