Static file and routing with asterisk template conflict

120 views Asked by At

I have a .NET 8 project with app.UseStaticFiles middleware and all the static files are served without problem.

After UseStaticFiles middleware I define the following minimal api which is supposed to fire whenever a not handled request appears.

app.MapGet("{*UrlParts}", (string? UrlParts) =>
{
    return Results.Content($"<h1>Hello World</h1>", "text/html");
}).WithOrder(10000);

This minimal api works fine and whenever I use a url which is not served by the server because there is not a controller or view to handle this request, I can see the Hello World contents.

The problem is that when I define this minima api endpoint, the static files are completely ignored and the contents of the minimal api appear on the screen.

The minimal api has been defined after the UseStaticFiles middleware and I also defined an order of 10000 to the minimal api so that it is going to have a lower priority.

I tried it with controllers and I have exactly the same result. I can not make both static files and controller / minimal api to work together.

Does anyone knows what Microsoft changed in .net 8 because in previous versions it was working, at least I remember using this combination.

1

There are 1 answers

0
Rena On BEST ANSWER

To resolve your issue, you need add the app.UseRouting() middleware:

app.UseStaticFiles();
app.UseRouting();

app.UseAuthorization();

app.MapControllers();
app.MapGet("{*UrlParts}", (string? UrlParts) =>
{
    return Results.Content($"<h1>Hello World</h1>", "text/html");

});