为什么 UseStaticFiles 和 UseDefaultFiles 之间的顺序很重要?

Why does order between UseStaticFiles and UseDefaultFiles matter?

我了解中间件的注册顺序。但是,并不一定是这样。

我注意到 UseDefaultFiles() 需要在 UseStaticFiles() 之前(可以被 巧妙地规避) .

我不明白的是为什么。它们是如何相撞的?!

我用谷歌搜索了这个问题,但对为什么订单在这个特殊情况下很重要的动机为零。只是它很重要...

来自docs

UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL rewriter that doesn't actually serve the file. Enable Static File Middleware via UseStaticFiles to serve the file.

中间件的顺序很重要,这就是为什么,例如,UseStaticFiles 必须在 UseMvc 之前,因为 MVC 引擎将处理所有请求。在这种情况下,UseDefaultFiles 只是重写 URL 并将其传递给 UseStaticFiles 中间件来提供服务。

UseDefaultFiles() 应该总是在 UseStaticFiles().

之前

这是因为 UseDefaultFiles 重写了 URLs。使用静态文件仅服务于 URLs。

如果文档服务发生在 URL 重写之前,那么您可能无法获得默认文档服务。

参考:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2#serve-a-default-document

摘自 Static files in ASP.NET Core 上的文档(在提供默认文档下,有一个 重要 注释)。

UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL rewriter that doesn't actually serve the file. Enable Static File Middleware via UseStaticFiles to serve the file.

基于此,在提供实际文件 (UseStaticFiles) 之前首先设置 URL 重写器 (UseDefaultFiles) 很重要。
如果不这样做,UseStaticFiles 中间件将首先启动,但对应用程序根目录的请求不会告诉中间件要服务哪个 'file'。当您确保首先进行重写时,对应用程序根目录的请求将被重写为对(其中一个)默认文件的请求。