DEV Community

Dominic Pascasio
Dominic Pascasio

Posted on

Blazor Web App - WebAssembly Hosted in .NET8 and .NET9

If you don't need Blazor server and you just want to load WebAssembly resources to the client first before rendering and running anything, this is the starter template configuration for you.

Project Template

dotnet new blazor -o MyApp -f net9.0 -int WebAssembly -ai

  • -o MyApp - output
  • -f net9.0 - target framework
  • -int WebAssembly - interactivity
  • -ai - all interactive, applies the config at the top level

This creates MyApp.sln, MyApp and MyApp.Client project folders. If you want to add WebApi, configure it in MyApp project.

This still has prerendering! To remove it entirely, edit MyApp/Components/App.razor:

Change this:

<HeadOutlet @rendermode="InteractiveWebAssembly" />
...
<Routes @rendermode="InteractiveWebAssembly" />
Enter fullscreen mode Exit fullscreen mode

to this:

<HeadOutlet @rendermode="new InteractiveWebAssemblyRenderMode(prerender: false)" />
...
<Routes @rendermode="new InteractiveWebAssemblyRenderMode(prerender: false)" />
Enter fullscreen mode Exit fullscreen mode

Note: Server prerendering gives unintended output and behavior when you want to run things in WebAssembly like redirect in AuthorizeRouteView>NotAuthorized. Removing server prerendering means removing the illusion of quick initial load.

Authentication/Authorization

If you want to authorize access to pages entirely on WebAssembly, allow anonymous on blazor components in MyApp/Program.cs:

app.MapRazorComponents<App>()
    .AllowAnonymous() //disables server-side authorization for Blazor
    .AddInteractiveWebAssemblyRenderMode()
    .AddAdditionalAssemblies(typeof(MyApp.Client._Imports).Assembly);
Enter fullscreen mode Exit fullscreen mode

Note: Server-side authorization of Blazor prevents you from loading the entire WebAssembly app when you type secure page in the address bar (e.g.: "/profile"). Since we will authorize in the client-side, we can bypass server authorization.

Warning! Client side is not secure. When page access / authorization is done on the client-side, there should be a final validation and authorization in your Web API when processing requests.

Final Thoughts:

  • This does not cover PWA but it can be a starting point.

Top comments (0)