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
CodePudding user response:
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.