ASP.NET 核心管道中的静态文件中间件应该放在什么位置?

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

我正在使用 ASP.NET Core 2.1。我认为静态文件中间件应该出现在 mvc 中间件之前 - 不需要 运行 通过 mvc 的请求只是为了服务 css 文件。

所以我的顺序是这样的:

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

但是,当我打开调试级别日志记录时,我注意到如果缺少静态文件,它会 运行 到 Microsoft.AspNetCore.Builder.RouterMiddleware 并显示 Request did not match any routes,然后 运行s 我的 ErrorController 并针对该请求发出 404。

所以:

为了让它更轻,你可以有一个像这样的自定义中间件:

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();
});

虽然您必须在数组中包含每个静态文件夹,但它确保直接 return 一个 404 而无需继续路由。

is this the correct order for the pipeline?

是的,是的。

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?

首先,您丢失的静态文件请求正在通过异常处理程序、HSTS、HTTPS 重定向和 StatusCodePagesWithReExecute 中间件,但让我们忽略它们,因为没有什么有趣的。请求只是通过它们。

然后由静态文件中间件处理。中间件很快就明白了,那个文件丢失了,只是让你的请求运行下一个中间件,这是MVC中间件。

MVC 中间件查看其路由 table 并找到 "catchAll" 路由并让 ErrorController 处理请求。这就是 ErrorController.

处理丢失文件的原因

P.S。我想你有 "catchAll" 路由是这样的:

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

            routes.MapRoute("catchAll", "{*.}", new { controller = "Error", action = "Error404" }
        });