简体   繁体   中英

Avoid adding virtual directory to path on an ASP.NET 5 application

On an ASP.NET 5 MVC view I have the following:

<header style="background-image: '/assets/poster.jpg')">

The folder "assets" is inside wwwroot ...

This works fine but when I host the project on the server under a virtual directory I need to add the virtual directory name to the path:

<header style="background-image: '/virtualdirectory/assets/poster.jpg')">

How can I avoid this?

Interestingly , This will work

<img src='~/assets/poster.jpg'/>

But, this won't

<div style="width:990px; height:99px; background-image: url('~/assets/poster.jpg')"> </div>

For your inline style, you can use the Url.Content helper method to generate the application absolute path.

The below code should work.

<div style="width: 100px; height: 100px; 
            background-image:url('@Url.Content("~/assets/poster.jpg")')"></div>

If you want it in a css class, you can simply use the relative path.

.myTest {
    background-image: url('../assets/gravatar.png');
     width:100px;height: 50px;
}

Assuming your css file is under a directory(Ex:css) which is a sibling to assets folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM