DEV Community

skyslide22
skyslide22

Posted on

How To Use HttpClient on a .NET8 Prerendered Blazor App with Auto/Wasm Rendermode

Using the http client in a blazor ssr app can be annoying, the following error would be thrown when the blazor wasm component is prerendered on the server:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.

The correct registration and usage of the http client on the client will not work when prerendering is enabled:

// Project.Client/Program.cs (the wasm project)
builder.Services.AddScoped(sp => new HttpClient { 
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) 
});

// Project.Client/Pages/FetchTest.razor
@page "/FetchTest"
@inject HttpClient httpClient
@rendermode InteractiveWebAssembly

<div>...</div>

@code
{
    protected override async Task OnInitializedAsync()
    {
        var res = await httpClient
            .GetFromJsonAsync<YourType>("api/fetchtestdata");
        ^^^^^^^^^^^ will fail at this point in ssr ^^^^^^^^^^
        // ... rest
    }
}
Enter fullscreen mode Exit fullscreen mode

But there is a solution/workaround for this!
Just disable any http client usage in the prerendering, like early return in the OnInitialized method, before the http client is actually used.

Here an example:

@page "/FetchTest"
@inject HttpClient httpClient
@rendermode InteractiveWebAssembly
@using System.Runtime.InteropServices

<div>...</div>
@code
{
    protected override async Task OnInitializedAsync()
    {
        var isPrerendering = RuntimeInformation.ProcessArchitecture != Architecture.Wasm;

        Console.WriteLine("prerendering: " + isPrerendering);

        if(isPrerendering)
            return;

        var res = await httpClient
            .GetFromJsonAsync<YourType>("api/fetchtestdata");

        // ... rest
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the error is gone and the blazor component with webassembly rendermode is working prerendered.

The server will log prerendering: True and the console in the browser will log prerendering: False.

Google, ChatGTP did not help that much, took a while to find this solution – actually from SamBerk on this post: https://stackoverflow.com/questions/60589776/detecting-server-pre-rendering-in-blazor-server-app

Top comments (0)