【问题标题】:Search priority for views using EmbeddedFileProvider使用 EmbeddedFileProvider 搜索视图的优先级
【发布时间】:2017-04-10 12:27:15
【问题描述】:

我有这个代码拉取视图作为资源嵌入到我引用的程序集中:

services.Configure<RazorViewEngineOptions>(options =>
    {
        options.FileProviders.Add(new EmbeddedFileProvider(typeof(SomeTypeInMyAssembly).GetTypeInfo().Assembly));
    });

它成功地在嵌入位置 (Views\Shared\Components\ViewComponentName\Default.cshtml) 中找到视图。在查看任何程序集之前,我需要它首先搜索当前项目中的文件,这样我可以在程序集中创建默认值,并允许在主项目中“覆盖”(相同的路径)。任何人都知道如何做到这一点?我仍在尝试通过源代码来解决这个问题。

不,ViewLocationExpander 不是答案。我需要使用完全相同的路径和文件名,谢谢。

【问题讨论】:

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


    【解决方案1】:

    原来有两种选择:

    1. 添加 options.FileProviders.Add(HostingEnvironment.ContentRootFileProvider); 就在EmbeddedFileProvider 之前。 (HostingEnvironment 只是被拍了 来自Startup() 构造函数并本地存储在Startup 类中。磁盘上的物理文件(也可能在缓存中)将在程序集版本之前找到。
    2. 用你自己的类型包装EmbeddedFileProvider(实现IFileProvider)并传入IHostingEnvironmentGetFileInfo() 方法是 在尝试定位文件时调用。这 IHostingEnvironment实例用于检测物理 根目录下的文件,如果本地文件存在则返回NotFoundFileInfo

      public virtual IFileInfo GetFileInfo(string subpath)
      {
          if (_HostingEnvironment != null)
          {
              var filepath = Path.Combine(_HostingEnvironment.ContentRootPath, subpath.TrimStart('/'));
              if (File.Exists(filepath))
                  return new NotFoundFileInfo(filepath);
          }
          return _EmbeddedFileProvider.GetFileInfo(subpath)
      }
      

      并将其添加到Startup.ConfigureServices():

      services.Configure<RazorViewEngineOptions>(options =>
      {
          options.FileProviders.Add(new MyEmbeddedFileProvider(typeof(SomeTypeInTheTargetAssembly).GetTypeInfo().Assembly, HostingEnvironment));
          });
       }
      

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 1970-01-01
      • 2019-05-21
      • 2011-10-09
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      相关资源
      最近更新 更多