How to map fallback in ASP .NET Core Web API so that Blazor WASM app only intercepts requests that are not to the API

To recap the problem, when somebody makes a request to:

https://yourapp.com/api/someendpoint

and /api/someendpoint can’t be found, they’re taken to a Blazor page. This default behaviour is weird. For requests starting with /api, they were expecting an HTTP Status Code and probably a JSON object too, but instead, they got HTML. Maybe they don’t even use your app. Maybe they’re not even human (more likely they’re a piece of software).

This is how you send them an HTTP Status Code instead.
On your controllers:

[Route("api/[controller]")]
public class SampleController : ControllerBase
{
    // ...
}

In Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // ...
    app.UseStaticFiles();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
        endpoints.MapControllers();
        endpoints.Map("api/{**slug}", HandleApiFallback);
        endpoints.MapFallbackToFile("{**slug}", "index.html");
    });
}

private Task HandleApiFallback(HttpContext context)
{
    context.Response.StatusCode = StatusCodes.Status404NotFound;
    return Task.CompletedTask;
}

Leave a Comment