gpt4 book ai didi

c# - 扩展 HttpClient

转载 作者:行者123 更新时间:2023-11-30 13:47:43 26 4
gpt4 key购买 nike

我正在尝试创建一个扩展 httpclient 但仍然是抽象的类。

public abstract class Repository : HttpClient
{
public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
//retry logic here
var response = await base.SendAsync(request, cancellationToken);
while (!IsValid(response))
{
Attempts++;
response = await Retry(request, cancellationToken);
}
Attempts = 0;
return response;
}
public int Attempts { get; set; }
public abstract bool IsValid(HttpResponseMessage response);
public abstract Task<HttpResponseMessage> Retry(HttpRequestMessage request, CancellationToken cancellationToken);
public abstract Type GetPageForUri(Uri uri);
public abstract Task<object> GetItems(Uri uri);
}

但是当子类调用 getStringAsync 时它不会调用 Repository 中的 SendAsync

public class EmailClient : Repository
{
public override bool IsValid(HttpResponseMessage response)
{
return response.IsSuccessStatusCode;
}
public override Task<HttpResponseMessage> Retry(HttpRequestMessage request, CancellationToken cancellationToken)
{
return base.SendAsync(request, cancellationToken);
}
public override Type GetPageForUri(Uri uri)
{
return typeof(EmailPage);
}
public override async Task<object> GetItems(Uri uri)
{
var emails = await GetStringAsync(uri);
return emails;
}
}

我做错了什么?我应该制作一个 HttpClientHandler 并将其包含在 HttpClient 中吗?如果有任何不同,我会尝试阅读有关虚拟的内容。但我不明白为什么它没有被调用。谁能帮帮我?

最佳答案

HttpClient 是围绕 HttpMessageHandler 实现(通常是 HttpClientHandler,大多数运行时实现都支持的特性的属性)的薄包装器

实际上有一个 HttpMessageHandler 基类用于装饰器,例如您的重试场景 DelegatingHandler,您可以像这样实现它:

类似于:

public class RetryMessageHandler : DelegatingHandler
{
readonly int retryCount;

public RetryMessageHandler(int retryCount)
: this(new HttpClientHandler(), retryCount)
{
}

public RetryMessageHandler(HttpMessageHandler innerHandler, int retryCount)
: base(innerHandler)
{
this.retryCount = retryCount;
}

public override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
HttpResponseMessage response = null;

for (int i = 0; i<=retryCount; i++)
{
response = await base.SendAsync(request, cancellationToken);

if (response.IsSuccessStatusCode)
{
return response;
}
}

return response;
}
}

然后你会像这样使用它:

HttpClient httpClient = HttpClientFactory.CreatePipeline(new HttpClientHandler(), 
new [] { new RetryMessageHandler(3) });

var response = await httpClient.SendAsync(request);

此外,我建议您的 EmailClient 包装/依赖于 HttpClient,而不是扩展它。 (有关原因的更多信息,请谷歌“组合与继承”)

关于c# - 扩展 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15716399/

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