Prerendering your Blazor WASM application with .NET 5 (part 2 - solving the missing HttpClient problem)
In part 1 we saw how to set up your Blazor WASM site for prerendering.
This means you can serve your application nice and quickly to your users without making them wait for Blazor WASM to finish loading.
However, we were left with a bit of a problem.
When you navigate to the /FetchData
page and hit refresh you get an error that HttpClient
hasn’t been registered.
InvalidOperationException: Cannot provide a value for property ‘Http’ on type ‘ExampleApp.Client.Pages.FetchData’. There is no registered service of type ‘System.Net.Http.HttpClient’.
Here’s the problem:
If you attempt to navigate directly to FetchData
your Server app will attempt to prerender it (just as it did with Counter or any of the other components).
However, this means it will attempt to execute OnInitializedAsync
on the server, at which point it will attempt to retrieve the weather data using HttpClient
.
The problem is, we haven’t registered HttpClient
as a dependency in the Server project, so it falls over.
Now we could just go ahead and register HttpClient
in the Server project’s Startup.cs
file, however then we’d be using HTTP to go from the Server project to itself, just to load the weather data!
Dan Roth’s .NET 5 samples demonstrate a handy alternative way to address this problem.
If we abstract away the logic for retrieving weather data we can make sure it works on both the server and the client.
Legacy .NET web apps causing you grief?
Build modern, reliable web applications, faster with .NET and Blazor.
Build better .NET web appsAnother layer of abstraction#
Currently FetchData.razor
uses the HTTPClient
directly…
FetchData.razor (markup)
This makes a HTTP call to the API exposed by the Server project.
This call will fail when prerendering because the Server project hasn’t been configured to know anything about HttpClient.
If we adopt Dan’s approach we can replace this with a call to an interface.
FetchData.razor (markup)
We’ll need to define the interface itself. This needs to go in the Shared
project so both Client and Server can access it.
Shared\IWeatherForecastService.cs
Now we can create two implementations of that interface.
Get weather data on the client (in the browser)#
When running on the client we still need to fetch the data via an HTTP GET request to the server.
So this implementation (Client.Data.WeatherForecastService
) can make the exact same HTTP call our component was making directly before.
Client\Data\WeatherForecastService.cs
Get weather data on the server#
For the server implementation we don’t need to go via HTTP and can instead fetch the weather data directly (in a more realistic scenario this would likely come from a query to a database or similar).
To make this work we can take the code which currently lives in the WeatherForecastController
and move it into a new WeatherForecastService
class.
Server\Data\WeatherForecastService.cs
This wil be invoked by the FetchData.razor
component when it’s initially (pre)rendered on the server.
Now we need to replace the code in WeatherForecastController
with a call to this service.
NOTE
We still need a controller
If the component is going to call WeatherForecastService
directly you might wonder why we need the controller at all?
Don’t forget, when our app runs in the browser (the client) it will still be using HTTP to fetch this data. This controller acts as the API endpoint for these requests, so the client can continue to interact with our application over HTTP.
It just so happens that on the server we can invoke the WeatherForecastService
directly (without going via an HTTP request).
Register the two implementations of IWeatherForecastService#
Now we need to make sure we register the relevant implementations in each project.
Client\Program.cs
Server\Startup.cs
With that, when the app is prerendered it will use Server.Data.WeatherForecastService
on the server.
When running in the browser it will use Client.Data.WeatherForecastService
(which uses HttpClient
but ultimately executes the same code in the server project, via Web API).
OnInitializedAsync is called twice#
The final thing to note here is that data will be retrieved twice when prerendering this way; once on the server when prerendering, then again on the client when Blazor WASM has finished loading.
This is really obvious when viewing the weather example because it’s random data so you see it appear then change when Blazor WASM kicks in…
NOTE
Why the double call?
When you opt to use prerendering your components are rendered once using the “static prerenderer” on the server. At this point OnInitializedAsync
is invoked.
The resulting static HTML is sent back to be displayed in the browser.
After the browser has displayed this HTML it continues to load the Blazor WASM app. Once that’s done it renders the component (on the client) and calls OnInitializedAsync
again, hence the new data being retrieved and displayed.
At the time of writing the only guidance I can find from Microsoft about how to handle this refers to Blazor Server app prerendering, but unless I’m missing something it would apply here too…
NOTE
.NET 6 News - Improvements are coming!
.NET 6 will ship with a way to preserve state between renders (significantly reducing the weird effects you get when the data is retrieved and rendered twice).
But, in the meantime…
The suggested solution is to cache the data on the server.
This doesn’t stop the second call being made to but it does reduce round trips to your database and also ensures the data is consistent between the prerender and subsequent client-side render.
I’ve seen two ways to do this:
Use memory cache#
One option is to add a little memory caching to the server version implementation of IWeatherForecastService
.
Server\Data\WeatherForecastService
This ensures the exact same data will be returned from memory for the second request (or indeed for any other requests made within the 30 seconds before the cached entry expires).
Make the service a singleton#
In Dan Roth’s .NET 5 samples it wasn’t initially clear to me why the “random” data remained consistent between the two renders, then I spotted the answer!
He has the WeatherForecastService
registered as a singleton in Server\Startup.cs
.
The GetForecast
method in Server.Data.WeatherForecastService
then adds forecasts to a _forecasts
field, until a certain count has been reached.
Server\Data\WeatherForecastService.cs
This means there’s just one instance of this service in memory running on the server, so it doesn’t matter how many times you call this method, if you’re passing the same arguments you’ll get the same data back.
Effectively this is also an in-memory cache, just implemented in a slightly different way…
In summary#
It’s entirely possible to make your data fetching (and calls to other services) work when you opt to prerender your Blazor WASM application.
You just have to be aware that your component’s OnInitializedAsync
method will be called twice.
You can use an interface to abstract the logic for this, then have a client implementation which delegates to HTTP to fetch the data (when running on the client) and a server implementation which fetches the data directly.
When prerendering OnInitializedAsync
will be called twice (once on the server, then again on the client) for any components that are prerendered on the server.
You can mitigate this by using caching to avoid roundtrips to your database etc. and to ensure consistent data is returned in both cases.
Grab the source code for the completed example here.
Further reading#
- Part 1 - Prerendering your .NET 5 Blazor WASM applications
- Dan Roth’s .NET 5 samples
- Chris Sainty’s post on prerendering pre .NET 5 Blazor WASM applications
All posts in To .NET 5 and beyond
- Does .NET 6 fix Blazor Prerendering?
- Update the HTML head from your Blazor components
- From site.css to component styles
- Render Blazor WASM components in your existing MVC/Razor Pages applications
- Prerendering your Blazor WASM application with .NET 5 (part 1)
- Prerendering your Blazor WASM application with .NET 5 (part 2 - solving the missing HttpClient problem)