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

标签 c# asp.net asp.net-core

我创建了一个 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/

相关文章:

c# - AjaxControlToolkit AjaxFileUpload 无法上传 IIS 保留文件类型

c# - 使用多个线程从 mysql 表中读取数据

c# - System.IO.Directory.GetFiles() 没有列出所有文件

c# - 如何让 ASP.NET 按钮执行 jQuery 代码

c# - ASP.NET Core 2.0+ 中 JwtBearerOptions.SaveToken 属性的用途是什么?

c# - 组件内的 Blazor 双向绑定(bind)文本区域

c# - 事件对使用 TaskCompletionSource 的异步方法

asp.net - 如何确定 iTextSharp Basefont 默认样式

javascript - 如何使用 jQuery 过滤 DropDownList 中的选项

c# - 为什么自动 modelstate 返回 400 状态代码而不是 422?