I have a project that requires retrieving files from outside itself on the server its hosted on. For now, I’m just grabbing a Javascript file but it will eventually grab other things. I tried out changing the content root path in Program.cs to allow this and it worked beautifully. But I noticed that the original relative links to Javascript and css files still worked without any changes.
For example this path, "~/css/site.css", still works despite changing the content root path and not telling it to specifically look in my project’s own wwwroot folder. The external file must use a more specific path. For example: "~/some-other-project/wwwroot/js/myscripts.js".
Now this is all fine and actually preferred behavior but I want to know why it’s working this way. Does the project check its own wwwroot folder first before looking elsewhere in the folder specified in the content root path? I want to understand the behavior behind this so I can feel more confident in using this method.
EDIT:
Here is a repo with as an example: https://github.com/love-bird-13/Custom-Content-Path-Test
The first commit is just setting up two basic .Net 6 projects without any changes. The second commit contains all the changes I made to reproduce what I’m talking about.
2
Answers
This is explained in the docs in the web root section:
And
About your question
The Serve files outside wwwroot by updating IWebHostEnvironment.WebRootPath topic specifies below.
So the behavior you describe is applicable while in
development
environment mode.You’ll notice that when changing the
ASPNETCORE_ENVIRONMENT
environment variable to something else thanDevelopment
– which is the default while developing – the files inwwwroot
won’t be served anymore.That same topic gives some approaches for below scenarios.
In case you want static content to only be served from the customized path instead of the default
wwwroot
, then the easiest might just be to delete thatwwwroot
folder.In case you want to combine
wwwroot
with a custom folder, then you add an additionalapp.UseStaticFiles
inProgram.cs
; here belowAssets
is a custom folder with some static files, but it can be any absolute path that is reachable.