【问题标题】:How to access resources in a .net class library from web request如何从 Web 请求访问 .net 类库中的资源
【发布时间】:2015-08-27 21:17:28
【问题描述】:

设置: 我有一个 .net 4.5 类库,它嵌入资源(例如图像)以供其他 ASP.NET MVC 项目重用。例如,类库(名为 BlockTypesLibrary)的路径如下:

  • 块类型库(项目)
    • 静态
      • img
        • 方块.png

我将 Block.png 的属性设置为 Build Action == "Embedded Resource" 和 Copy Type to Output Directory == "Do Not Copy"。

现在在我的 MVC 项目中,我引用了 BlockTypesLibrary.dll 并使用 Reflector,我看到列出的资源正常:

  • 块类型库
    • BlockTypesLibrary.dll
    • 资源
      • BlockTypesLibrary.Static.img.Block.png

在模板中,我尝试以多种不同方式访问该资源,但不能。例如:

  <div >
    <img src="~/BlockTypesLibrary.Static.img.Block.png" alt="Block">
  </div>

任何想法如何使这项工作?我还需要将 .cshtml 模板作为资源包含在类库中。

【问题讨论】:

  • 你使用的是什么版本的 MVC?
  • 因为我没有硬样本,所以我不会将其作为答案发布,但我认为您需要使用 ResourceManager 类从中提取命名资源(您的图像 Block.png)作为对象的程序集
  • @从不使用 MVC 4 或 MVC 5。
  • AHA 发现了一个我认为会有所帮助的现有问题。看看stackoverflow.com/questions/12523098/…,我认为它可以满足您的需求。
  • @DavidW 哇,我做了不同的搜索,但没有出现!会看看,看看这是否对我有用。谢谢!

标签: c# .net embedded-resource


【解决方案1】:

您需要一个控制器来从另一个程序集中加载嵌入的资源图像。

图书馆项目

public class ResourceLoader
{
    public static byte[] Load(string file)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            // load resource
            typeof(ResourceLoader).Assembly.GetManifestResourceStream(file).CopyTo(ms);

            return ms.ToArray();
        }
    }

    public static string[] Files()
    {
        // return list of embeded resource available
        return typeof(ResourceLoader).Assembly.GetManifestResourceNames();
    }

}

MVC 项目

public class ImgController : Controller
{

    [Route("~/img/embed/{*filename}")]
    public ActionResult Embed(string filename)
    {
        byte[] content = ResourceLoader.Load(filename);
        string mime = MimeMapping.GetMimeMapping(filename);

        return File(content, mime);
    }
}

View.cshtml

<div >
    <img src="/img/embed/BlockTypesLibrary.Static.img.Block.png" alt="Block">
</div>

【讨论】:

  • 我提高了对此的投票计数,因为它似乎是解决问题的一个优雅的解决方案。但是,我暂时不会接受,因为我很难在我的解决方案中实现这一点。但那是因为我使用的 CMS 框架覆盖了一些标准的 MVC 框架,所以我需要在该约束范围内适应这个解决方案,到目前为止还没有运气。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-24
  • 2012-05-11
  • 1970-01-01
  • 2022-11-07
  • 2023-02-14
  • 1970-01-01
  • 2012-12-06
相关资源
最近更新 更多