c# - 在 Razor 网页上显示静态 .png 图像

标签 c# html asp.net asp.net-core .net-core

我开始学习.NET Core C#。尽管我很生疏,但我以前有过一些 C# 经验。我有一个小型静态网络应用程序,运行良好,我正在尝试将其迁移并扩展为学习练习。我完全陷入困境,只是试图显示我的图像,特别是 Circle_logo.png。

网页显示(虽然布局似乎已经困惑 - 那是明天的问题!),但所有图像都有损坏的链接。

我已经花了几个小时搜索 Google 医生,我一定错过了一些东西,因为看起来仅仅为了在 .Net Core 中显示一个简单的 .png 文件就需要做很多繁重的工作?

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();
    });
}

当我加载应用程序时,图像未显示在index.cshtml 上。它们显示为损坏的链接,如果单击,则会显示 404 错误。

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

文件夹结构:

Folder Structure in project

最佳答案

您需要将图像文件夹放入 wwwroot 中,并在 Startup 类(您已经拥有)的配置方法中添加所需的中间件:

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

在您的 Razor 页面中,您可以按如下方式引用图像:

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

src 中的 ~ 符号表示我的网站的“根”或本例中的 wwwroot 文件夹。

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

关于c# - 在 Razor 网页上显示静态 .png 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61426965/

相关文章:

C#,将列表中的列转换为一行

c# - 哪种存储少量结构化数据的方式最安全?

html - <tr> 上的 onMouseOver 不覆盖带有背景图像的单元格

javascript - 如何让JS变量在页面刷新后保留值?

javascript - 在 html() 之前删除Class

asp.net - 为什么我的应用程序在 AppHarbor 上死机了?

c# - 使用 FillPath 创建带孔的多边形

asp.net - 如何在 ASP.NET MVC 中设置整个区域的授权?

c# - foreach row in datatable 为每一列添加一个asptablerow和asptablecell

c# - 如何从音频文件中获取 musicbrainz 轨道信息