Home > Software engineering >  Why app.UseStaticFiles() is terminating middleware.?
Why app.UseStaticFiles() is terminating middleware.?

Time:01-23

Why app.UseStaticFiles() is terminating variable, though it calls a method so that next middleware can execute.

Here is the code of Invoke method StaticFileMiddleware, where the _next(context) is called to call the next middleware in the pipeline. https://github.com/dotnet/aspnetcore/blob/87144203fb2471183a5ed240a8ceb3f4836dfab0/src/Middleware/StaticFiles/src/StaticFileMiddleware.cs#L82

CodePudding user response:

UseStaticFiles is designed to serve static files like images, JS files. It returns the file when it finds a request path match for the given file.

There is no need to do further processing of the request (as the file is found and can be returned to the user) so It will not call the upcoming middlewares in the request pipeline.

so the position of the UseStaticFiles in the pipeline configuration is very important.

If the file is not found then it will call the next middleware in the pipeline.

See this code here, it returns if the file is found.

private Task TryServeStaticFile(HttpContext context, string? contentType, PathString subPath)
{
    var fileContext = new StaticFileContext(context, _options, _logger, _fileProvider, contentType, subPath);

    if (!fileContext.LookupFileInfo())
    {
        _logger.FileNotFound(fileContext.SubPath);
    }
    else
    {
        // If we get here, we can try to serve the file
        return fileContext.ServeStaticFile(context, _next);
    }

    return _next(context);
}

Check this code also.

  • Related