简体   繁体   中英

How do I properly serve images from the wwwroot to razor pages in a “Page” subfolder?

I have a JavaScript function that creates a fading slideshow. It uses images in the directory:

"wwwroot/images/backgrounds"

If I load a page that's directly inside the Pages folder, the images load properly. But if I load a page that's inside a subfolder, the browser tries to get the images from inside that folder instead of from the root folder.

So instead of

"localhost/images/backgrounds/bg1.jpg"

I get

"localhost/subfolder in 'Pages' folder/images/backgrounds/bg1.jpg"

I'm still new to this, so I'm not sure why the wwwroot folder isn't serving the images properly, but I set my default page to one in the same subfolder and it works perfectly, so I'm at a loss at to what's wrong.

Any ideas or solutions would be greatly appreciated at this point.

You're loading your images from a relative path - that is, the path that's exactly under the current directory . You want it to be based on an absolute path - that is, off of the same directory, no matter where the page is. To do that, use a slash in the beginning of your path: /wwwroot/images/backgrounds

This is actually by design - imagine you had sub-directories in your web application that needed their own images. You can then load an image, like images/pageBackground.png that's relative to each page the user is on - very convenient! Just remember that leading slash - which means start this path from the virtual root of the application instead of the current sub-directory - and you'll get the right file!

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