Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should static files middleware be in the ASP.NET Core pipeline?

I'm using ASP.NET Core 2.1. I thought the static files middleware should come before the mvc middleware - no need to run a request through mvc just to serve a css file for example.

So I have them in this order:

app.UseExceptionHandler(/*...*/)
app.UseHsts();
app.UseHttpsRedirection();
app.UseStatusCodePagesWithReExecute(/*...*/);
// and lastly:
app.UseStaticFiles();
app.UseMvc(/*...*/);

However when I turn on debug level logging, I notice that if a static file is missing, it runs through Microsoft.AspNetCore.Builder.RouterMiddleware and says Request did not match any routes, then runs my ErrorController and issues a 404 for that request.

So:

  • is this the correct order for the pipeline?
  • is there a way to avoid all this, or is it by design? e.g. Some "lighter" process to trigger a 404 without going through all that? Like maybe having static files middleware be first (not sure if that's wise/secure though)?
like image 381
lonix Avatar asked Jul 06 '18 10:07

lonix


People also ask

Which of the following middleware must be installed to serve static files in ASP.NET Core application?

ASP.NET Core application cannot serve static files by default. We must include Microsoft. AspNetCore. StaticFiles middleware in the request pipeline.

What is the default directory for static files in ASP.NET Core?

Static files are stored within the project's web root directory. The default directory is {content root}/wwwroot , but it can be changed with the UseWebRoot method.

What is middleware in .NET Core and how is it injected in the request pipeline?

Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component: Chooses whether to pass the request to the next component in the pipeline. Can perform work before and after the next component in the pipeline.

Where do you find the middleware in .NET Core?

A middleware is nothing but a component (class) which is executed on every request in ASP.NET Core application. In the classic ASP.NET, HttpHandlers and HttpModules were part of request pipeline. Middleware is similar to HttpHandlers and HttpModules where both needs to be configured and executed in each request.


Video Answer


2 Answers

is this the correct order for the pipeline?

Yes, it is.

However when I turn on debug level logging, I notice that if a static file is missing, it runs through Microsoft.AspNetCore.Builder.RouterMiddleware and says Request did not match any routes, then runs my ErrorController and issues a 404 for that request. Why?

First, your missing static file request is going through exception handler, HSTS, HTTPS redirection and StatusCodePagesWithReExecute middleware, but let's ignore them, because there is nothing interesting. Request just passes through them.

Then, it is processed by static files middleware. The middleware soon understands, that file is missing and just lets your request run to next middleware, which is MVC middlware.

MVC middleware looks through its route table and finds "catchAll" route and lets ErrorController process the request. That is the reason why missing files are processed by ErrorController.

P.S. I suppose you have "catchAll" route something like this:

app.UseMvc(routes =>
        {
            .... // your routes here

            routes.MapRoute("catchAll", "{*.}", new { controller = "Error", action = "Error404" }
        });
like image 102
Vitaliy Avatar answered Oct 30 '22 21:10

Vitaliy


To get it lighter you can have a custom middleware something like this:

var avoidFolders = new string[] { "js", "css" };

app.Use(async (context, next) => {
    if (avoidFolders.Contains(context.Request.Path.Value.Trim('/')))
        context.Response.StatusCode = 404;
    else await next();
});

Although you will have to include every static folder in the array, it makes sure to directly return a 404 without proceeding to routing.

like image 26
Neville Nazerane Avatar answered Oct 30 '22 19:10

Neville Nazerane