In Program.cs
:
builder.Services.AddHttpClient();
Read String using GET method
@page "/" @inject IHttpClientFactory ClientFactory <PageTitle>Index</PageTitle> <button @onclick="Button_Clicked">Call API</button> @code { private async Task Button_Clicked() { // read string using GET method var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5055/hello-world"); var client = ClientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } } }
Send and Read JSON using POST method
private async Task Button2_Clicked() { // send and read json using POST method var url = "http://localhost:5055/hello2"; var person = new Person() {FirstName = "Mahmood", LastName = "Ramzani"}; var json = JsonSerializer.Serialize(person); var data = new StringContent(json, Encoding.UTF8, "application/json"); var client = ClientFactory.CreateClient(); var response = await client.PostAsync(url, data); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } }
References
https://docs.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-6.0&pivots=server