CS1929 'IHttpClientFactory' does not contain a definition for 'GetFromJsonAsync'

Viewed 595

I got the message "CS1929 - 'IHttpClientFactory' does not contain a definition for 'GetFromJsonAsync'" on my Razor component page Index.razor in my Blazor Server project. I am trying to make an http request to connect the component to the database.

Below is the code in index.razor:

@page "/people"
@inject IHttpClientFactory httpClientFactory

<h3>People</h3>

@if (people == null)
{<text>Loading...</text>}
else if (people.Length == 0)
{ <text>No people have been added to this database.</text>}
else
{
<table>
    <thead>
        <tr>
            <th>ID</th>
            <th>Title</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Phone Number</th>
            <th>Email ID</th>
            <th>Address</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var person in people)
        {
            <tr>
                <td><a>Edit</a><button>Delete</button></td>
                <td>@person.ID</td>
                <td>@person.Title</td>
                <td>@person.FirstName</td>
                <td>@person.LastName</td>
                <td>@person.PhoneNumber</td>
                <td>@person.Email</td>
                <td>@person.Address</td>

            </tr>
        }
    </tbody>
</table>
}

@code {
    Person[] people { get; set; }

    protected override async Task OnInitializedAsync()
    {
        await LoadPeople();
    }
     
    async Task LoadPeople() => people = await httpClientFactory.GetFromJsonAsync<Person[]>("api/people");
}

And I added the line services.AddHttpClient(); under public void ConfigureServices(IServiceCollection services) in Startup.cs

The error is in the word httpClientFactory line async Task LoadPeople() => people = await httpClientFactory.GetFromJsonAsync<Person[]>

I even tried replacing it with the below but that just caused more errors so I removed it:

var http = httpClientFactory.CreateClient();
async Task LoadPeople() => people = await http.GetFromJsonAsync<Person[]("api/people");

What is the best way to fix this? I have been getting a new problem every time I manage to fix an old one while trying to connect http.

1 Answers

You have to install the System.Net.Http.Json package...

Provides extension methods for System.Net.Http.HttpClient and System.Net.Http.HttpContent that perform automatic serialization and deserialization using System.Text.Json.

Please, execute this in your nuget console:

Install-Package System.Net.Http.Json -Version 3.2.1

Code sample:

public void ConfigureServices(IServiceCollection services)
{
   // Chnage the url to yours
    services.AddHttpClient("ServerAPI", client => client.BaseAddress = 
        new Uri("https://localhost:44371/"));

    services.AddTransient(sp => 
           sp.GetRequiredService<IHttpClientFactory> 
           ().CreateClient("ServerAPI"));

}

And in your FetchData page:

@inject HttpClient  httpClient
Related