I have faced problem with accessing static files from wwwroot folder in ASP.NET Core application in release mode. I keep my static files in wwwroot folder and access them with a relative path, for example to access wwwroot/images/test.png for src attribute of img tag I specify /images/test.png and the picture loads correctly in local IIS Express development mode.
Now I have created Website in IIS Manager (TestWebsite) and deployed my web application to it, and also I created Application pool in site (TestApplicationPool) so that it’s hierarchy looks like this:
The problem I have faced is that after deploy my paths to static files has crashed and to access them I need to have /TestApplicationPool before any path (for the example above, now I need to specify /TestApplicationPool/images/test.png to access image). So my question is there any way we can configure ASP.NET application to always use current Application as content root path, so that we don’t need to specify nothing in path except the path of static file relative to wwwroot folder?
I have tried to get application name from ContentRootPath variable of IWebHostEnvironment and insert it before the path to the static file and in this case everything works, but it is inconvenient to do this every time we need to load static file from wwwroot folder.
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
In MVC views or Razor pages you can use a tilde and slash (~/) prefix on the path to represent the web root (wwwroot by default) in most places in your cshtml views/pages.
<img src="~/hello.jpg" />
This should translate to the correct path even when deployed under a virtual directory in IIS (like your example).
Relevant documentation about web root can be found here, and this mentions the ~/