Unable to resolve service for type 'System.Net.Http.HttpClient' 无法解析类型为'System.Net.Http.HttpClient'的服务。

8 浏览
0 Comments

Unable to resolve service for type 'System.Net.Http.HttpClient' 无法解析类型为'System.Net.Http.HttpClient'的服务。

我创建了一个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 InvokeAsync(string date)
    {
        using(var response = await _client.GetAsync($"/product/get_products/{date}"))
        {
            response.EnsureSuccessStatusCode();
            var products = await response.Content.ReadAsAsync>();
            return View(products);
        }
    }
}

我遇到了这个错误:

InvalidOperationException: 在尝试激活MyApp.ViewComponents.ProductsViewComponent时,无法解析类型“System.Net.Http.HttpClient”的服务。

我在Startup中的ConfigureServices方法中以这种方式注入了HttpClient

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

更新:

我也注册了ProductsViewComponent,但仍然遇到同样的错误。

0