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

Viewed 1049

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.

2 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"); 

You should do that like this:

@code{
    private List<Movie> movies;

    protected override async Task OnInitializedAsync()
    {
        var client = http.CreateClient("ServerAPI");        
        var response= await client.GetAsync("api/Movies");
        response.EnsureSuccessStatusCode();

        var responseContent = await response.Content.ReadAsStreamAsync();


        movies = await System.Text.Json.JsonSerializer.DeserializeAsync<List<Movie>> 
                      (responseContent,
             new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
    }
}

Hope this helps...

Related