I have this code which register HttpClient
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpClient("ServerAPI", client =>
client.BaseAddress = new Uri("http://localhost:xxxxx/"));
}
and to use it, I injected it at my Blazor razor page,
@page "/Movies/FetchMovies"
@inject IHttpClientFactory http;
@using System.Text.Json
<MovieList Movies="movies" />
@code{
private List<Movie> movies;
protected override async Task OnInitializedAsync()
{
var client = http.CreateClient("ServerAPI");
movies = await client.GetAsync<List<Movie>>("api/Movies");
//movies = await client.GetFromJsonAsync<List<Movie>>("api/Movies");
}
}
Problem is this line movies = await client.GetAsync<List<Movie>>("api/Movies"); gets an error:
The non-generic method 'HttpClient.GetAsync(string)' cannot be used with type arguments
I tried with movies = await client.GetFromJsonAsync<List<Movie>>("api/Movies") but also get an error.
If you wish to use the GetFromJsonAsync method instead, do the following:
System.Net.Http.JsonSystem.Text.Json and System.Net.Http.Jsoneither to your specific razor file, or to the /_Imports.razor file.
Now this code will the job...
movies = await client.GetFromJsonAsync<List<Movie>>("api/Movies");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With