【问题标题】:How to load an embedded image resource in a razor view, both are in a class library如何在剃刀视图中加载嵌入的图像资源,两者都在类库中
【发布时间】:2020-10-28 10:55:25
【问题描述】:

我有一个类库项目,在该项目中我有一个 Home Controller 和 Index 操作方法以及一个 Index 视图

在视图中,我正在加载 /Content/eagle.jpg 目录中的图像。 我构建项目并在另一个 MVC 项目中引用 dll,

现在,当我浏览 Home 控制器的 Index 操作方法时,我看到了视图,但缺少图像,如果有人知道如何实现这一点,请帮助。

注意:我将图像的“构建操作”设置为“嵌入式资源”

这是视图的代码

<h3>
This is Index
</h3>
<img src="~/Content/eagle.jpg" height="680" />

【问题讨论】:

标签: c# asp.net-mvc dll


【解决方案1】:

我遇到了同样的问题,我是这样解决的:

@using System.IO
@{
   var dir = $"file:///{Directory.GetCurrentDirectory()}";
}

<img src="@dir/Content/eagle.jpg" height="680" />

您还应该将文件复制到输出目录。

【讨论】:

    【解决方案2】:

    如果您的构建操作设置为embedded,您可以尝试使用此函数加载(.net core 3.1)

    public static byte[] LoadEmbedded(string Name, Assembly Asm = null)
    {
        var a = Asm ?? Assembly.GetCallingAssembly();
        var s = a.GetManifestResourceStream(a.GetName().Name + "." + Name);
        if (s != null)
        {
            var Buf = new byte[s.Length];
            s.Read(Buf, 0, Buf.Length);
            return Buf;
        }
        throw new Exception(Name + " resource not found");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多