Search code examples
c#api.net-7.0catch-allstaticfilehandler

.NET 7 API catch-all route without breaking static files


We are using attribute routing in a .NET 7 API project. In the startup we call UseStaticFiles() before calling MapController(). Something like this:

app
   .UseDefaultFiles()
   .UseStaticFiles()
   .MapControllers();

app.Run();

We are trying to create a catch all route like this:

 [Route("/{**catchAll}")]
 CatchNonExistingRoute()
{
 //implementation
}

This works. However, the catchAll route is taking precedence over the static files, which we don't want.

Is there any way around this?

I've been playing with the app.MapFallback method, but this also doesn't seem to do what I want.


Solution

  • Try explicitly calling UseRouting after UseStaticFiles (AFAIK otherwise it is implicitly called before everything else which makes CatchNonExistingRoute to have precedence over everything else):

    app
       .UseDefaultFiles()
       .UseStaticFiles()
       .UseRouting()
       .MapControllers();