gpt4 book ai didi

c# - 无法解析类型 'System.Net.Http.HttpClient' 的服务

转载 作者:太空狗 更新时间:2023-10-29 18:13:03 25 4
gpt4 key购买 nike

我创建了一个 ViewComponent 类,它使用 HttpClient 调用 REST API,这是代码:

public class ProductsViewComponent : ViewComponent
{
private readonly HttpClient _client;

public ProductsViewComponent(HttpClient client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
}

public async Task<IViewComponentResult> InvokeAsync(string date)
{
using(var response = await _client.GetAsync($"/product/get_products/{date}"))
{
response.EnsureSuccessStatusCode();
var products = await response.Content.ReadAsAsync<List<Products>>();
return View(products);
}
}
}

我收到这个错误:

InvalidOperationException: Unable to resolve service for type 'System.Net.Http.HttpClient' while attempting to activate MyApp.ViewComponents.ProductsViewComponent'

我以这种方式在 Startup 中可用的 ConfigureService 方法中注入(inject)了 HttpClient:

 services.AddHttpClient<FixturesViewComponent>(options =>
{
options.BaseAddress = new Uri("http://80.350.485.118/api/v2");
});

更新:

我也注册了ProductsViewComponent,同样的错误。

最佳答案

我有一个类似的问题 - 问题是双重注册:

services.AddHttpClient<Service>();
services.AddSingleton<Service>(); // fixed by removing this line

类似的例子[只是添加以澄清它不是特定于 AddSingleton,也不与订单相关。]

services.AddScoped<IService, Service>();  // fixed by removing this line
services.AddHttpClient<IService, Service>();

关于c# - 无法解析类型 'System.Net.Http.HttpClient' 的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52186856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com