I'm encountering an error in my Blazor WebAssembly application running on .NET 8. The error occurs when the application launches:
InvalidOperationException: Cannot provide a value for property 'Http' on type 'SGC.Client.Layout.NavMenu'. There is no registered service of type 'System.Net.Http.HttpClient'.
This is my Program.cs file on the client-side:
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddHttpClient();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddAuthorizationCore();
builder.Services.AddCascadingAuthenticationState();
builder.Services.AddSingleton<AuthenticationStateProvider, PersistentAuthenticationStateProvider>();
builder.Services.AddRadzenComponents();
builder.Services.AddScoped<DialogService>();
builder.Services.AddScoped<NotificationService>();
builder.Services.AddScoped<ContextMenuService>();
builder.Services.AddScoped<TooltipService>();
await builder.Build().RunAsync();
The error occurs when I inject HttpClient into any page. For example:
@page "/example"
@inject HttpClient Http
<h3>Example Page</h3>
How can I resolve this issue and correctly inject HttpClient into my Blazor WebAssembly application?
Ensured HttpClient is registered in the services in Program.cs.
@inject IEnumerable<HttpClient> HttpClients- as this will not throw if there are none registered, but you do then have to add code to get theHttpClientfrom the IEnumerable and allow for nulls.