简体   繁体   中英

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

im trying to do a http Post request in Blazor Server. I try do send a Username and a Password

this is the Part of the where i do the web Api call:

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; }
}

Here is my 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();

I know it's very messy but im already trying 6 hours to solve it:D

And this is the Error Message

错误信息

My goal is that it no longer crashes

If you need more information, just write a comment:D

When you in your Startup class do var app = builder.build(); you implicity say "I'm done registering services". So you need to move your builder.Services.AddHttpClient(); to somewhere before that line to make it work, it can't be at the end.

I would post a more full example of what I mean, but the code is in a screenshot which makes it to much work retyping everything.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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