当我尝试将类型化的客户端用于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正确设置类型化的客户端?
答案 0 :(得分:6)
IPStackService
的激活器(代码反射)在DI集合中找不到HttpClient
,这就是为什么您会收到异常(特别是services.AddTransient<IIPStackService, IPStackService>()
的原因)的原因。
顺便说一句,您已经在您的DI集合中两次添加了服务IPStackService
:
services.AddHttpClient<IPStackService>(...);
。services.AddTransient<IIPStackService, IPStackService>()
; 您只需要一个,并且由于您正在使用类型化的客户端,因此可以通过删除第二个并保留第一个来解决您的问题,并通过向实现中添加合同来稍微改变第一个,如下所示:< / p>
services.AddHttpClient<IIPStackService, IPStackService>(c =>
{
c.BaseAddress = new Uri(Configuration["IPStackURL"]);
});
AddHttpClient
将把HttpClinet
绑定到您的服务。
如果要使用services.AddTransient<IIPStackService, IPStackService>();
代替services.AddHttpClient
,则需要将HttpClinet
添加到DI集合中,如下所示:
services.AddTransient<HttpClient>();