繁体   English   中英

没有“System.Net.Http.IHttpClientFactory”类型的注册服务

[英]There is no registered service of type 'System.Net.Http.IHttpClientFactory

我试图在 Blazor 服务器中执行 http 发布请求。 我尝试发送用户名和密码

这是我拨打 web Api 电话的部分:

private IEnumerable<yolo> test = Array.Empty<yolo>();
private bool getBranchesError;
private bool shouldRender;

protected override async Task OnInitializedAsync()
{
     var request = new HttpRequestMessage(HttpMethod.Post, 
         "https://url.com");
    request.Headers.Add("Accept", "application/vnd.github.json");
    request.Headers.Add("User-Agent", "HttpClientFactory-Sample");
    var client = ClientFactory.CreateClient();
    var response = await client.SendAsync(request);

    if (response.IsSuccessStatusCode)
    {
        using var responseStream = await response.Content.ReadAsStreamAsync();
        test = await JsonSerializer.DeserializeAsync
            <IEnumerable<yolo>>(responseStream);
    }
    else
    {
        getBranchesError = true;
    }

    shouldRender = true;
}
    public class yolo
{
    [JsonPropertyName("name")]
    public string Name { get; set; }
}

这是我的 Program.cs

var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may 
want to change this for production scenarios, 
see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}  

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

//http Client
builder.Services.AddHttpClient();

我知道这很混乱,但我已经尝试了 6 个小时来解决它:D

这是错误消息

错误信息

我的目标是它不再崩溃

如果您需要更多信息,请写评论:D

当你在你的Startup class 做var app = builder.build(); 你含蓄地说“我已经完成了注册服务”。 所以你需要移动你的builder.Services.AddHttpClient(); 到那条线之前的某个地方使它工作,它不能在最后。

我会发布一个更完整的示例来说明我的意思,但是代码在屏幕截图中,这使得重新键入所有内容变得非常困难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM