Re-add proper API calls into Blazor WebAssembly template #55307
Description
As of .NET 8, the Blazor Web template with WebAssembly interactivity does not contain any example of calling a server API. The "weather forecast" page simply generates data on the client and thus only demonstrates how to render a table, not how to fetch data.
Actually calling a server API in all generality, accounting for all the main ways of setting up a site, is complicated by several factors, as pointed out by @mrpmorris:
- Deal with prerendering or auto mode. In these cases, you have to be able to load the data when running on WebAssembly and when running on the server. So you must either:
- Register
HttpClient
in DI with a base address on both server and client, and have the server call itself via HTTP - Or, have some interface representing the datastore, and set up both server and client implementations
- Register
- Avoid the double-render problem whereby the data is loaded twice (once for prerendering, once for interactivity)
- This is more complicated with per-page interactivity, since enanced nav doesn't currently work with persistent state
- Make this work sensibly with auth, including for both client and server data access
While typical apps don't usually have to solve all these problems simultaneously, we need to be able to demonstrate convenient, flexible patterns that do compose well with all the features and are clean enough to put them in the project template.
Solving this nicely likely depends on implementing some other features like #51584
Note for community: Recommendation for .NET 8 developers
As mentioned above, typical apps don't normally have to solve all these problems. It's always been simple to load data from the server with Blazor WebAssembly and that is still the case in .NET 8.
The easiest path is simply to disable WebAssembly prerendering, because then just about all the complexity vanishes. Whenever you used rendermode WebAssembly
(e.g., in App.razor
), replace it with new WebAssemblyRenderMode(prerender: false)
.
At that point your UI is just running in the browser and you can make HttpClient
calls to the server as normal.