Closed BrettSandham closed 8 months ago
A green dinosaur π¦ will be along shortly to assist. Stand-by ........
Hello @BrettSandham ... That's due to prerendering. The service won't be available on the server, so the error is thrown.
It's covered in a general way here :point_right: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0#client-side-services-fail-to-resolve-during-prerendering
For this specific case, there are two approaches to address it ...
Add the HttpClient
services server-side, so they will be there for when the Counter
component is prerendered. Use the following service registration in the main app's (the server app's) Program
file:
builder.Services.AddHttpClient();
It's covered by the Server pivot of the article :point_right: https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-8.0&pivots=server
Since your interactive render mode is WASM and if you don't need to prerender the Counter
component for any reason, you can prevent prerendering for the Counter
page with the following Razor directive at the top of the file ...
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
Therefore, it won't try to compile the component on the server, thus it won't π₯ on the missing HttpClient
services.
Covered at :point_right: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0#prerendering
Whichever direction you go, leave this issue open. I've been improving the guidance on these service scenarios, albeit slowly π due to all of the high priority issues that I'm still addressing. I'd like to use this issue to make further improvements to our coverage on this.
When I work on this, I'll take a couple of approaches to improve coverage ...
This issue will close automatically later when the PR merges, and I should be able to reach this in early '24. We're all just about to bug out of here for the βπβοΈ holiday break, so I won't be able to reach this until then.
Thanks for the issue and Happy New Year! ππΎππΊπ
Thank you! Was not expecting such a prompt response this time of the year. All the best to you and the whole team.
Description
Hi
I'm sure this is an ID10T user issue!
I am trying to follow https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-8.0&pivots=webassemblyn and cannot register an HttpClient Service. Minimum steps :
Error An unhandled exception occurred while processing the request. InvalidOperationException: Cannot provide a value for property 'Http' on type 'HttpClientIssue.Client.Pages.Counter'. There is no registered service of type 'System.Net.Http.HttpClient'.
[Enter feedback here]
Page URL
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-web-api?view=aspnetcore-8.0
Content source URL
https://github.com/dotnet/AspNetCore.Docs/blob/main/aspnetcore/blazor/call-web-api.md
Document ID
c7e59a08-1c60-32c2-75fd-33cb77ff7a5d
Article author
@guardrex