The solution is to use NotFound
in combination with UseStatusCodePagesWithReExecute
:
Step 1: Add the following to Program.cs
app.UseHttpsRedirection();
// Add this line
app.UseStatusCodePagesWithReExecute("/not-found");
app.UseStaticFiles();
...
Step 2: Add a dummy .razor page with the same url
@page "/not-found"
<My404Component />
Step 3: Add a NotFound renderfragment to Routes.razor
<Router>
<Found>
...
</Found>
<NotFound>
<LayoutView Layout="typeof(MyLayout)">
<My404Component />
</LayoutView>
</NotFound>
</Router>
The documentation states NotFound in Router is no longer supported, but this is actually not true, it still works but only if you do step 1 and 2 first, see https://github.com/dotnet/aspnetcore/issues/51203#issuecomment-1992085307