如何使用 PolicyHttpMessageHandler 作为 "standalone"?

How to use the PolicyHttpMessageHandler as "standalone"?

我只是想创建一个简单的测试,我在其中使用 DelegateHandlers 来实例化 HttpClient,而不带 Asp.net 核心包。 我有 2 个删除处理程序

如何将两者结合起来并传递给 HttpClient

var policy = HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
var pollyHandler = new PolicyHttpMessageHandler(policy);
var http = new HttpClient(new ThrottlingDelegatingHandler(MaxParallelism, pollyHandler));

上面给我一个错误:System.InvalidOperationException : The inner handler has not been assigned.

PolicyHttpMessageHandler 没有可以传递 innerHandler 的构造函数。

我怎样才能做到这一点?

您必须将最内部处理程序中的 InnerHandler 设置为 HttpClientHandler,如下所示:

var policy = HttpPolicyExtensions.HandleTransientHttpError().CircuitBreakerAsync(5, TimeSpan.FromSeconds(30));
var pollyHandler = new PolicyHttpMessageHandler(policy);

//New line
pollyHandler.InnerHandler = new HttpClientHandler();

var http = new HttpClient(new ThrottlingDelegatingHandler(MaxParallelism, pollyHandler));

您基本上必须在管道中设置下一个处理程序。


供参考:this is how HttpClient is constructed if no handler is specified

#region Constructors

public HttpClient() : this(new HttpClientHandler())
{
}

public HttpClient(HttpMessageHandler handler) : this(handler, true)
{
}

public HttpClient(HttpMessageHandler handler, bool disposeHandler) : base(handler, disposeHandler)
{
    _timeout = s_defaultTimeout;
    _maxResponseContentBufferSize = HttpContent.MaxBufferSize;
    _pendingRequestsCts = new CancellationTokenSource();
}

#endregion Constructors

其中 baseHttpMessageInvoker class