I'm following the Microsoft tutorial on Blazor. I'm getting the 'HttpClient doesn't contain a definition for 'GetFromJsonAsync' error when trying to use this extension method in the Index.razor
page. System.Net.Http.Json (v. 6.0.0)
is installed.
This is what my Index.razor file looks like:
@page "/"
@using System.Net.Http.Json
<div class="main">
<h1>Blazing Pizzas</h1>
<ul class="pizza-cards">
@if (specials != null)
{
@foreach (var special in specials)
{
<li style="background-image: url('@special.ImageUrl')">
<div class="pizza-info">
<span class="title">@special.Name</span>
@special.Description
<span class="price">@special.GetFormattedBasePrice()</span>
</div>
</li>
}
}
</ul>
</div>
@code
{
// List of special offers
List<PizzaSpecial> specials = new();
protected override async Task OnInitializedAsync()
{
specials = await HttpClient.GetFromJsonAsync<List<PizzaSpecial>>(NavigationManager.BaseUri + "specials");
}
}
I've tried installing a newer version of System.Net.Http.Json
but the error persisted.
I'm following the Microsoft tutorial on Blazor. I'm getting the 'HttpClient doesn't contain a definition for 'GetFromJsonAsync' error when trying to use this extension method in the Index.razor
page. System.Net.Http.Json (v. 6.0.0)
is installed.
This is what my Index.razor file looks like:
@page "/"
@using System.Net.Http.Json
<div class="main">
<h1>Blazing Pizzas</h1>
<ul class="pizza-cards">
@if (specials != null)
{
@foreach (var special in specials)
{
<li style="background-image: url('@special.ImageUrl')">
<div class="pizza-info">
<span class="title">@special.Name</span>
@special.Description
<span class="price">@special.GetFormattedBasePrice()</span>
</div>
</li>
}
}
</ul>
</div>
@code
{
// List of special offers
List<PizzaSpecial> specials = new();
protected override async Task OnInitializedAsync()
{
specials = await HttpClient.GetFromJsonAsync<List<PizzaSpecial>>(NavigationManager.BaseUri + "specials");
}
}
I've tried installing a newer version of System.Net.Http.Json
but the error persisted.
1 Answer
Reset to default 0Your httpclient isn't directly available in the index.razor component, so you can inject it manually
Update your .razor file
@inject HttpClient Http
@inject NavigationManager NavigationManager
Update your OnInitializedAsync to use:
await Http.GetFromJsonAsync
Http
and you will see it requires you to register http service in Program.cs viabuilder.Services.AddHttpClient();
and you also need to inject this service into your razor component by@inject HttpClient HttpClient
to resolve compilation error. By the way, for test purpose you'd better not to use a newer version to avoid version conflict. – Tiny Wang Commented Feb 6 at 6:10