skip to Main Content

I’m trying a simple web app. Created a /wwwroot/error.html.

When requesing in the browser /error.html it works, no problem at all.

Program.cs

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseStaticFiles();

app.Run();

Then I’ve added a .MapGet after the app.UseStaticFiles(), and when requesting /error.html in the browser is not working, it renders "Hello World!"

Program.cs

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.UseStaticFiles();

app.MapGet("/{*path}", () => "Hello World!");

app.Run();

When using static files middlewares before any route mapping, if the requested file is found it must serve it, isn’t it?

Thank you all!

2

Answers


  1. The order of middleware execution matters in ASP.NET Core.
    In your case, app.UseStaticFiles(); is placed before app.MapGet("/{*path}", () => "Hello World!"); in your middleware pipeline. When a request for /error.html comes in, it first goes through the UseStaticFiles middleware. Since the file exists in the wwwroot folder, the static file middleware will handle the request and serve the file.

    If you want the MapGet middleware to handle the request before the static files middleware, you can change the order of middleware registration:

    var builder = WebApplication.CreateBuilder(args);

    var app = builder.Build();

    app.MapGet("/{*path}", () => "Hello World!");

    app.UseStaticFiles();

    app.Run();

    By placing app.MapGet before app.UseStaticFiles, you are saying, "first, try to handle the request using this MapGet middleware, and if it doesn’t match, then let the static files middleware handle it."

    Login or Signup to reply.
  2. Add explicit UseRouting call (if it is not called it is added by default somewhere at start of pipeline and you will have your catch-all route to have a precedence):

    app.UseStaticFiles();
    app.UseRouting();
    app.MapGet("/{*path}", () => "Hello World!");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search