【问题标题】:Show static .png image on Razor webpage在 Razor 网页上显示静态 .png 图像
【发布时间】:2020-08-09 02:58:49
【问题描述】:

我开始学习 .NET Core C#。尽管我很生疏,但我有一些以前的 C# 经验。我有一个运行良好的小型静态 Web 应用程序,我正在尝试将其迁移并扩展为学习练习。我只是想显示我的图像,特别是 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

文件夹结构:

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    src 中的 ~ 符号表示我的网站的“根”或在这种情况下 wwwroot 文件夹。

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

    【讨论】:

    • 啊!它总是简单的事情。谢谢一百万!
    【解决方案2】:

    使用

    启用静态文件服务
    app.UseStaticFiles();
    

    他们的默认文件夹是wwwroot

    尝试将图像移动到此文件夹(或者在您的情况下移动到文件夹 wwwroot/image)。

    【讨论】:

      【解决方案3】:

      尝试将“图像”文件夹从“页面”移动到“wwwroot”。

      所以您的图片将位于“wwwroot/image/circle_logo.png”,可以通过“/image/circle_logo.png”访问

      【讨论】:

        猜你喜欢
        • 2014-03-20
        • 1970-01-01
        • 2010-10-10
        • 2011-09-24
        • 1970-01-01
        • 2020-09-24
        • 1970-01-01
        • 2014-07-29
        • 1970-01-01
        相关资源
        最近更新 更多