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

问题描述 投票:0回答:1

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

这是我进行 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

c# blazor httprequest
1个回答
6
投票

当您在

Startup
课程中执行
var app = builder.build();
时,您会含蓄地说“我已完成注册服务”。因此,您需要将
builder.Services.AddHttpClient();
移动到该行之前的某个位置才能使其正常工作,它不能位于末尾。

builder.Services.AddHttpClient();

// Adding services needs to go before this one!
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();

© www.soinside.com 2019 - 2024. All rights reserved.