Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The non-generic method 'HttpClient.GetAsync(string)' cannot be used with type arguments

Tags:

blazor

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.

like image 381
Steve Avatar asked Apr 25 '26 22:04

Steve


1 Answers

If you wish to use the GetFromJsonAsync method instead, do the following:

  1. Install the package System.Net.Http.Json
  2. reference the namespaces: System.Text.Json and System.Net.Http.Json

either 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"); 
like image 104
Peter Morris Avatar answered Apr 28 '26 22:04

Peter Morris