繁体   English   中英

如何在 http 客户端注册通用接口?

[英]How to register generic interfaces in http client?

在我的 aspnet 核心项目中,我使用的是 HttpClient,我有通用接口和 class,但我无法在启动时注册它们。

我的界面看起来像:

public interface IHttpClientWrapper<T> where  T : class
{
        Task<T> GetAsync(string url, string authType, string token, CancellationToken cancellationToken);
}

我的 class 看起来像:

    public class HttpClientWrapper<T> : IHttpClientWrapper<T> where T : class
    {
        private readonly HttpClient _client;

        public HttpClientWrapper(HttpClient client)
        {
            _client = client;
        }

        public async Task<T> GetAsync(string url, string authType, string token,
            CancellationToken cancellationToken)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, url);
            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authType, token);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));

            using (var response = await _client.SendAsync(request,
                HttpCompletionOption.ResponseHeadersRead,
                cancellationToken))
            {
                var stream = await response.Content.ReadAsStreamAsync();
                response.EnsureSuccessStatusCode();
                return stream.ReadAndDeserializeFromJson<T>();
            }
        }
    }

我想达到的目标:

 services.AddHttpClient<IHttpClientWrapper<T>, HttpClientWrapper<T>>()
                .ConfigurePrimaryHttpMessageHandler(handler =>
                    new HttpClientHandler
                     {
                     AutomaticDecompression = System.Net.DecompressionMethods.GZip
                   });

我尝试过但失败了:

services.AddTransient(typeof(IHttpClientWrapper<>),typeof(HttpClientWrapper<>)).ConfigureOptions(
                new HttpClientHandler
                {  
                    AutomaticDecompression = System.Net.DecompressionMethods.GZip
                });

简而言之,我需要以某种方式注册 AutomaticDecompression = System.Net.DecompressionMethods.GZip 如果可能的话它可以与 Transient

  1. 我不确定你为什么要注册 IHttpClientWrapper。 如果它是暂时的,那么您可以在需要时创建它。

  2. 如果您有充分的理由使用 DI,那么您可以使 class 非泛型并使方法泛型:

public interface IHttpClientWrapper
{
    Task<T> GetAsync<T>(string url, string authType, string token, CancellationToken cancellationToken);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM