Robert
Robert

Reputation: 393

.NET Core and Razor cannot load image in img src 404

I have application written in .NET Core and View in Razor. This is standard Login.cshtml view generated from Visual Studio Identity. In this view I want to include img:

<img src="../../../../Assets/0rdfEnHw.jpeg" alt="">

Image is added in folder:

MyApp:
-Areas
  -Identity
    -Pages
      -Account
       -Login.cshtml
-Assets
  -0rdfEnHw.jpeg

And in browser I have error:

GET https://localhost:5001/Assets/0rdfEnHw.jpeg 404

Upvotes: 2

Views: 2775

Answers (2)

Zhi Lv
Zhi Lv

Reputation: 21656

By default, the Static files are stored within the project's web root directory. The default directory is {content root}/wwwroot.

To serve files outside of web root (like your scenario: using the Assets folder), you could configuring the Static File Middleware as follows:

        app.UseStaticFiles(new StaticFileOptions
        {
            FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Assets")),
            RequestPath = "/Assets"
        });

Then, the view page as below:

 <img src="~/Assets/Image2.jpg" />

[Note] By using the above method, since it changes the default static file location, it might cause the CSS files and JQuery file not load success (because, they are using the wwwroot folder as the default folder, you have to change the path for them),

So, I suggest you change the Assets folder location, try to drag it into the wwwroot folder, like this:

enter image description here

Then, using the following code to load image.

 <img src="~/Assets/Image2.jpg" />

By using this method, there is no need to change the Static File Middleware, just using the default setting:

app.UseStaticFiles();

More detail information about the Static files in ASP.NET Core, please check this link.

Upvotes: 5

Muhammad Kamran Aslam
Muhammad Kamran Aslam

Reputation: 658

Use relative path like this,

<img src="~/Assets/0rdfEnHw.jpeg" />

And Make Sure your assets folder is under wwwroot folder, as static content in Asp.Net Core is served under this.

Upvotes: 0

Related Questions