当我尝试将类型化的客户端用于HttpClient时,收到错误消息:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.2

这是我的设置:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddDefaultAWSOptions(Configuration.GetAWSOptions());

    services.AddHttpClient<IPStackService>(c =>
    {
        c.BaseAddress = new Uri(Configuration["IPStackURL"]);
    });

    services.AddHttpContextAccessor();

    services.AddTransient<IIPStackService, IPStackService>();
}


控制器:

[Route("api/[controller]")]
    [ApiController]
    public class RenderController : ControllerBase
    {
        private IConfiguration _configuration;
        private readonly ILogger _logger;
        private IIPStackService _ipMetaDataService;

        public RenderController(IConfiguration configuration,
                                ILogger<RenderController> logger,
                                IIPStackService ipStackService)
        {
            _configuration = configuration;
            _ipStackService = ipStackService;
            _logger = logger;
        }

        [HttpGet]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [Produces("text/plain")]
        public async Task<ActionResult> GetAsync(string hostId, string clientUtc)
        {
            var ip = Common.ResolveIPAddress(HttpContext);

            var ipMetaData = await _ipStackService.GetByIPAsync(ip, _configuration["AccessKey"]);

            // removed for clarity

            return allowed ? Ok(true) : Ok(null);
        }
    }


服务:

public class IPStackService : IIPStackService
{
    private readonly ILogger _logger;
    private readonly HttpClient _httpClient;

    public IPStackService(ILogger<IPStackService> logger, HttpClient client)
    {
        _logger = logger;
        _httpClient = client;
    }

    public async Task<IPMetaDataModel> GetByIPAsync(string ip, string accessKey)
    {
        var ipMetaData = new IPMetaDataModel();

        var response = await _httpClient.GetAsync($"/{ip}?access_key={accessKey}");
        response.EnsureSuccessStatusCode();

        // removed for clarity

        return ipMetaData;
    }
}


收到错误:


  处理请求时发生未处理的异常。
  InvalidOperationException:无法解析类型的服务
  尝试激活时出现“ System.Net.Http.HttpClient”
  “ WebScreen.Gate.Services.IPStackService”。
  Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type
  serviceType,Type ImplementationType,CallSiteChain,callSiteChain,
  ParameterInfo []参数,布尔型throwIfCallSiteNotFound)


如何为HttpClient正确设置类型化的客户端?

最佳答案

IPStackService的激活器(代码反射)在DI集合中找不到HttpClient,这就是为什么您会收到异常(特别是services.AddTransient<IIPStackService, IPStackService>()的原因)的原因。

顺便说一句,您在DI集合中两次添加了服务IPStackService


services.AddHttpClient<IPStackService>(...);
services.AddTransient<IIPStackService, IPStackService>();


您只需要一个,并且由于您正在使用类型化的客户端,因此可以通过删除第二个并保留第一个来解决您的问题,并通过向实现中添加契约来稍微改变第一个,如下所示:

services.AddHttpClient<IIPStackService, IPStackService>(c =>
{
     c.BaseAddress = new Uri(Configuration["IPStackURL"]);
});


AddHttpClient将负责将HttpClient绑定到您的服务。



如果要使用services.AddTransient<IIPStackService, IPStackService>();而不是services.AddHttpClient,则需要将HttpClient添加到DI集合中,如下所示:

services.AddTransient<HttpClient>();

关于c# - ASP.NET Core类型客户端中的IHttpClientFactory,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56091875/

10-12 04:06