MapFallbackToPage on subfolder in ASP.NET Core

Viewed 2438

I'm trying to create a fallback route to a Razor page inside my ASP.NET Core application so I can host a server-side Blazor app on a subpath. Creating a fallback route from the root works as described in the documentation. But I want it my fallback on routes /Admin/*.

My current code looks like this:

app.UseEndpoints(endpoints =>
{
    // ...
    endpoints.MapFallbackToPage("/Admin", "/Admin/_Host");
});

I've also tried to use the following setup:

app.UseEndpoints(endpoints =>
{
    // ...
    endpoints.MapFallbackToPage("/Admin/{*segment}", "/Admin/_Host");
});

Both configurations end up generating a 404 when I enter a URL for a page that exists in my Blazor app. I verified that navigating within the Blazor app using <NavLink> does work.

What would be the correct way of doing this?

1 Answers

It turns out that I should have used the following piece of code:

app.UseEndpoints(endpoints =>
{
    // ...
    endpoints.MapFallbackToPage("/Admin/{**segment}", "/Admin/_Host");
});

Note the ** in the pattern. It's a recursive mapping for all segments in the URL that come after the /Admin part. I was only using a single star, which caused the deeply nested URLs to not match the pattern.

I learned that the pattern for the MapFallbackToPage method accepts a regular routing pattern.

For those interested in learning more: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0

Alternative solution

You can also add a @page "/Admin/{**segment}" directive at the top of _Host.cshtml. You'll have to remove the MapFallbackToPage call in Startup.cs.

Related