Oğuzhan KARAGÜZEL

OĞUZHAN KARAGÜZEL

Software Developer

ASP.NET MVC: CSS, JS and Images Not Loading on /home/index?

Author: Oğuzhan KARAGÜZEL ·


I had been living with this problem for a long time and finally solved it myself. I searched everywhere and found nothing. The funny part: just as I was about to post my fix on Stack Overflow, I noticed the question had already been asked there, and answered. So this problem is hard even to describe. That's why I wanted a title that anyone running into it would actually find.

The Problem

Open the site at its root, say localhost:7148, and everything is in place. Go to /home/index and the page is bare: no CSS, no JavaScript, no images. Plain HTML, like the picture above.

Open the browser's developer tools and you'll see a pile of failed GET requests: this file not found, that image not found.

Why It Happens

It's a path problem. At the root you are on the same level as the wwwroot folder; at /home/index you are not. The browser looks for each file relative to the address you're on, and doesn't find it. The paths in your views most likely look like this:

HTML
<img src="img/profilephoto.jpeg" />
<img src="/img/profilephoto.jpeg" />
<img src="../img/profilephoto.jpeg" />

On /home/index, for example, img/profilephoto.jpeg is requested as /home/img/profilephoto.jpeg, which doesn't exist. A path starting with / goes to the site root, but if the app runs in a subfolder (an IIS virtual directory, say), that points to the wrong place too.

Your JS and CSS files in the assets folder were probably linked the same way.

The Fix: a Tilde (~)

There are two ways out. The first is to register static files by hand, the way you register services. Believe me, you don't need it. You might if you keep files in a folder other than wwwroot, but don't do that: put every static file inside wwwroot.

The second, and the real fix, is to tell Razor "always look for these files in wwwroot". All it takes is a ~:

HTML
<img src="~/img/profilephoto.jpeg" />
<script src="~/js/script.js"></script>
<link rel="stylesheet" href="~/css/site.css" />

Start every file path with ~/. Whatever address the page is opened from, Razor then always looks for the file in wwwroot, and it produces the right address even when the app runs in a subfolder.

So the tilde matters. Use it whenever you give a file path in a script, img or link tag, and you won't run into this problem again.

Happy coding.