Reputation: 39210
I understand that the order of registration for middleware may matter. However, it's not given that it's necessarily the case.
I noticed that UseDefaultFiles() needs to precede UseStaticFiles() (which can neatly be circumvented by UseFileServer()).
What I don't understand is why. How do they collide?!
I've googled the issue but got zero motivation on why the order is significant in this particular case. Only that it is of importance...
Upvotes: 17
Views: 9916
Reputation: 15621
Taken from the documentation on Static files in ASP.NET Core (under Serve a default document, there's an important note).
UseDefaultFiles
must be called beforeUseStaticFiles
to serve the default file.UseDefaultFiles
is a URL rewriter that doesn't actually serve the file. Enable Static File Middleware viaUseStaticFiles
to serve the file.
Based on this, it's important to first setup the URL rewriter (UseDefaultFiles
) before serving the actual file (UseStaticFiles
).
If you don't, the UseStaticFiles
middleware will kick in first, but a request to the root of the application won't tell the middleware which 'file' to serve. When you make sure the rewrite is in place first, a request to the root of the application will have been rewritten to be a request for (one of the) default file(s).
Upvotes: 20
Reputation: 5634
UseDefaultFiles() should always be before UseStaticFiles().
This is because UseDefaultFiles rewrite the URLs. Use Static files only serves the URLs.
If serving of document happens earlier than URL rewrite, then you may not get default document served.
Upvotes: 3
Reputation: 119056
From the docs:
UseDefaultFiles
must be called beforeUseStaticFiles
to serve the default file.UseDefaultFiles
is a URL rewriter that doesn't actually serve the file. Enable Static File Middleware viaUseStaticFiles
to serve the file.
The order of middleware does matter, this is why, for example, UseStaticFiles
has to come before UseMvc
as the MVC engine will handle all of the requests. In this case, UseDefaultFiles
is simply rewriting the URL and passing it on to the UseStaticFiles
middleware to serve.
Upvotes: 7