Is there any way to set a generic root path for content in ASP.NET Core?

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:

hfnmy

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.

Answers:

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.

Method 1

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.

For example:

<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 ~/
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/?view=aspnetcore-5.0&tabs=windows#web-root


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x