我在遵循此指南时遇到问题:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-2.1#basic-usage
这是我的configureservices
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
这是我的页面
public class IndexModel : PageModel
{
private readonly IHttpClientFactory httpClientFactory;
public IList<Blog> Blog { get; set; }
public IndexModel(IHttpClientFactory httpClientFactory)
{
this.httpClientFactory = httpClientFactory;
}
public async Task OnGetAsync()
{
}
}
浏览到我的页面时收到以下错误:
InvalidOperationException: Unable to resolve service for type 'System.Net.Http.IHttpClientFactory' while attempting to activate 'WebApplication1.Pages.Blogs.IndexModel'.
我错过了什么吗?
感谢您的任何建议
致谢
foo
答案 0 :(得分:0)
http客户端工厂不会在您需要的地方注入httpclient工厂, 为您注入httpclient 尝试
public class SampleService : ISampleService
{
private readonly HttpClient _httpClient;
public SampleService(HttpClient httpClient)
{
_httpClient = httpClient;
}
答案 1 :(得分:0)
我认为您必须创建 HttpClient:
private readonly HttpClient httpClient;
public IndexModel(IHttpClientFactory httpClientFactory)
{
this.httpClient = httpClientFactory.CreateClient();
}