【发布时间】:2019-02-10 16:49:33
【问题描述】:
我创建了一个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:尝试激活 MyApp.ViewComponents.ProductsViewComponent 时无法解析“System.Net.Http.HttpClient”类型的服务
我以这种方式将HttpClient注入到Startup中可用的ConfigureService方法中:
services.AddHttpClient<FixturesViewComponent>(options =>
{
options.BaseAddress = new Uri("http://80.350.485.118/api/v2");
});
更新:
我也注册了ProductsViewComponent,同样的错误。
【问题讨论】:
-
您是如何在您的 IoC 容器中注册
HttpClient的? -
ProductsViewComponent!=FixturesViewComponent. -
@KirkLarkin 我同时注册了
ViewComponent,但我仍然遇到同样的错误 -
所有这些代码都很好。在
Startup.cs中添加服务后是否重建?除此之外,这可能是一个愚蠢的问题,但是您确定将其添加到正确的项目中吗?你确定你真的保存了文件吗?不知道还能去哪里,因为否则它会起作用。这些都不是奇怪或不正常的。 -
@KirkLarkin 我在这里创建了一个聊天室:chat.stackoverflow.com/rooms/179489/viewcomponent-injection cmets 太长了
标签: c# asp.net asp.net-core