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.
You have to install the System.Net.Http.Json package...
Please, execute this in your nuget console:
Code sample:
And in your FetchData page: