【发布时间】:2019-04-02 18:25:38
【问题描述】:
我正在尝试设置一个 IHttpClientFactory,我想知道在创建它时如何向它发送参数,这些参数我需要分配给重试策略。
我正在使用 .Net Core 2.2 和 Microsoft.Extensions.Http.Polly,我已阅读此帖子 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2
我有这是 Startup.cs
services.AddHttpClient("MyClient", c =>
{
c.BaseAddress = new Uri("http://interface.net");
c.DefaultRequestHeaders.Add("Accept", "application/json");
})
.AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3, _ => TimeSpan.FromMilliseconds(600)));
我是这样用的
private readonly IHttpClientFactory _iHttpClientFactory;
public ValuesController(IHttpClientFactory iHttpClientFactory)
{
_iHttpClientFactory = iHttpClientFactory;
}
public async Task<ActionResult<string>> Get()
{
var client = _iHttpClientFactory.CreateClient("MyClient");
var response = await client.GetAsync("/Service?Id=123");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsStringAsync();
return result;
}
我想知道当我执行 CreateClient 时是否有办法发送参数,用于在 AddTransientHttpErrorPolicy 中分配给 retryCount 和 sleepDuration,在这种情况下分别为 3 和 600,因为我需要创建具有不同 retryCounts 的客户端和 sleepDurations,这些值可以改变。
类似的东西
var retryCount = 5;
var sleepDuration = 400;
var client = _iHttpClientFactory.CreateClient("MyClient", retryCount, sleepDuration);
或者其他方式?
【问题讨论】:
-
最新 (.net 6) 如何在Make HTTP requests using IHttpClientFactory in ASP.NET Core
标签: c# asp.net-core dotnet-httpclient polly