gpt4 book ai didi

c# - 如何将 PolicyHttpMessageHandler 用作 "standalone"?

转载 作者:行者123 更新时间:2023-12-05 03:27:10 31 4
gpt4 key购买 nike

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

  • ThrottlingDelegatingHandler
  • PolicyHttpMessageHandler(来自 Polly 包)

如何将两者结合起来并传递给 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

关于c# - 如何将 PolicyHttpMessageHandler 用作 "standalone"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71542054/

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