简体   繁体   中英

How to load an embedded image resource in a razor view, both are in a class library

I have a class library project, and in that project I have a Home Controller and and Index action method and an Index view

In the view I am loading an image that is in the /Content/eagle.jpg directory. I build the project and reference the dll in another MVC project,

Now when I browse the Index action method of the Home controller I get the view, but the Image is missing, If someone knows how to achieve this please help.

Note: I am setting the "Build Action" for image to "Embedded Resource"

this is code of the view

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

I had the same problem and I resolved it in this way:

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

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

You should also copy file to output directory.

If your build action is set to embedded , you can try loading with this function (.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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM