elmokennedy
elmokennedy

Reputation: 23

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:

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.

Upvotes: 2

Views: 1686

Answers (1)

jbuch
jbuch

Reputation: 131

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

Upvotes: 0

Related Questions