我正在尝试为ASP.Net Core 2.2应用程序的特定端点的所有API调用创建可由控制器和常规函数访问的服务。每当我尝试注入HttpClient类时,在可以访问功能之前都会发生错误/
我已经按照文档中所示设置了startup.cs,并将构造函数的输入减少为HttpClient,所以我知道这是问题的根源。我已经以我能想到的所有方式将HttpClient添加到Startup.cs类的configure services部分中。
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
...
// adding ability to make basic http calls
services.AddHttpClient<IServerInventoryService, ServerInventoryService>(c =>
{
c.BaseAddress = new Uri("https://serverinventory.cooperatorsgroup.ca/api/");
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler()
{
AllowAutoRedirect = false,
UseDefaultCredentials = true
};
});
}
控制器:
private ILogger<ServerInventoryApiController> logger;
private IHttpClientFactory clientFactory;
private readonly IServerInventoryService ServerInventoryService;
public ServerInventoryApiController(ILogger<ServerInventoryApiController> _logger, IServerInventoryService _service, IHttpClientFactory httpClientFactory)
{
ServerInventoryService = _service;
logger = _logger;
clientFactory = httpClientFactory;
}
APIService:
public class ServerInventoryService : IServerInventoryService
{
private HttpClient client;
// private readonly IConfiguration configuration;
public ServerInventoryService(HttpClient httpClient)
{
client = httpClient;
}
每次调用服务结果是:
“ InvalidOperationException:找不到类型为'ApplicationInventory.Services.ServerInventoryService'的合适的构造函数。确保类型是具体的,并且已为公共构造函数的所有参数注册了服务。“