DMur
DMur

Reputation: 659

Show static .png image on Razor webpage

I am starting to learn .NET Core C#. I have some previous C# experience although I am very rusty. I had a small static web app which was working fine and am trying to migrate it across and expand it as a learning exercise. I'm completely stuck just trying to get my images to display, specifically circle_logo.png.

The webpage displays (Although the layout seems to have gone haywire - thats tomorrows problem!), but all the images have broken links.

I've spent a few hours now trawling doctor Google and I must be missing something, because it appears like there is a lot of heavy lifting necessary just to display a simple .png file in .Net Core?

Index.cshtml

<img src="/image/circle_logo.png" width="40" height="40" style="margin:0px 20px;" alt="Logo Image">

Startup.cs

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}

When I load my app, the images are not showing on index.cshtml. They display as broken links and if clicked show a 404 error.

This localhost page can’t be foundNo webpage was found for the web address: https://localhost:44319/index.html
HTTP ERROR 404

Folder Structure:

Folder Structure in project

Upvotes: 2

Views: 3176

Answers (3)

Isma
Isma

Reputation: 15209

You need to put your image folder inside wwwroot and add the required middleware in the method Configure of your Startup class (which you already have):

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

In your razor page you can reference the image as follows:

<img src="~/image/circle_logo.png" width="40" height="40" style="margin:0px 20px;" alt="Logo Image">

The ~ symbol in the src means "root" of my website or the wwwroot folder in this case.

Source: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

Upvotes: 3

DonSleza4e
DonSleza4e

Reputation: 731

Try to move your 'image' folder from 'Pages' to 'wwwroot'.

So your image will be at 'wwwroot/image/circle_logo.png' can be accessible via "/image/circle_logo.png"

Upvotes: 1

Martin Staufcik
Martin Staufcik

Reputation: 9502

Serving static files is enabled with

app.UseStaticFiles();

and the default folder for them is wwwroot.

Try moving the image into this folder (or in your case into the folder wwwroot/image).

Upvotes: 1

Related Questions