修复了 header 和基础 url 定义以用于 Restsharp 的整个程序

Fixed header and base url definition to be used in the whole program for Restsharp

我有一些httpclient的通用化操作,我想在restsharp client中应用这些操作。

我正在分享示例 httpclient 代码

1.Startup

在启动文件中将服务注册为容器的过程 像这里一样,我能够订阅 di 容器并自定义 httpclient,我不必在整个服务中一遍又一遍地定义 baseapiurl。是否可以在 restsharp

中实现此方法
 services.AddHttpClient<ICatalogService, CatalogService>(opt =>
        {
            opt.BaseAddress = new Uri($"{serviceApiSettings.GatewayBaseUri}/{serviceApiSettings.Catalog.Path}");
        }).AddHttpMessageHandler<ClientCredentialTokenHandler>();

2.ClientCredentialTokenHandler.cs

   public class ClientCredentialTokenHandler:DelegatingHandler
    {
        private readonly IClientCredentialTokenService _clientCredentialTokenService;

        public ClientCredentialTokenHandler(IClientCredentialTokenService clientCredentialTokenService)
        {
            _clientCredentialTokenService = clientCredentialTokenService;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",await _clientCredentialTokenService.GetToken());

            var response = await base.SendAsync(request,cancellationToken);

            if (response.StatusCode==System.Net.HttpStatusCode.Unauthorized)
            {
                throw new UnAuthorizeException();
            }
            return response;
        }
  }

当从每个 httpclient 向外部服务发出请求时,这种结构使我免于重复代码。 RestClient 是否有类似的解决方案?

是的,您可以添加默认参数(不仅仅是headers)并指定RestClient的基地址。

var client = new RestClient(baseUrl).AddDefaultHeader(key, value);

这里,AddDefaultHeader是一个环绕AddDefaultParameter,它接受除BodyParameter之外的任何参数类型。

关于委托处理程序,您可以使用 RestClient 构造函数之一,它接受 HttpMessageHandler 的实例,或者 ConfigureMessageHandler 属性 [=18] =].在文档中是described