ASP.NET Core ViewLocationExpander 无法在其他程序集中找到视图

Soh*_*deh 3 c# asp.net-mvc razor asp.net-core

我有以下解决方案:

src
   /Web
   /Web.Admin
        /Controller
          /TestControllr.cs
        /Views
            /Test
               /Index.cshtml
Run Code Online (Sandbox Code Playgroud)

我将应用程序部分用于单独的“我的应用程序部分”:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        var adminAssembly = Assembly.Load(new AssemblyName("Web.Admin"));

        services.AddMvc().AddApplicationPart(adminAssembly);

        services.Configure<RazorViewEngineOptions>(options =>
        {
           options.ViewLocationExpanders.Add(new AdminViewLocationExpander());

        });
    }
}
Run Code Online (Sandbox Code Playgroud)

并创建一个 ViewLocationExpander 名称AdminViewLocationExpander

public class AdminViewLocationExpander : IViewLocationExpander
{
    public void PopulateValues(ViewLocationExpanderContext context)
    {
    }

    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        const string adminAssembly = "Web.Admin";

        var adminViewsLocations = new []
        {
            $"/{adminAssembly}/Views/{{1}}/{{0}}.cshtml",
            $"/{adminAssembly}/Views/Shared/{{0}}.cshtml"
        };

        viewLocations = adminViewsLocations.Concat(viewLocations);

        return viewLocations;
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用此 URL 运行应用程序时,localhost:6046/Test/Index得到以下信息:

 InvalidOperationException: The view 'Index' was not found. The following 
 locations were searched:
 /Web.Admin/Views/Test/Index.cshtml
 /Web.Admin/Views/Shared/Index.cshtml
 /Views/Test/Index.cshtml
 /Views/Shared/Index.cshtml
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Joe*_*tte 5

在我的项目中,我将视图作为嵌入资源保留在单独的类库项目/程序集中,打包为 nuget。例如,这是一个带有嵌入式视图的项目

我不需要自定义 IViewLocationExpander 来找到它们。相反,我创建一个像这样的扩展方法:

public static RazorViewEngineOptions AddCloudscribeSimpleContentBootstrap3Views(this RazorViewEngineOptions options)
{
    options.FileProviders.Add(new EmbeddedFileProvider(
                typeof(Bootstrap3).GetTypeInfo().Assembly,
                "cloudscribe.SimpleContent.Web.Views.Bootstrap3"
          ));

    return options;
} 
Run Code Online (Sandbox Code Playgroud)

然后在主应用程序的启动中我像这样添加它们:

services.AddMvc()
.AddRazorOptions(options =>
{
    options.AddCloudscribeSimpleContentBootstrap3Views();


});
Run Code Online (Sandbox Code Playgroud)

在我的带有嵌入视图的类库中,我只是将它们像平常一样放在 Views 文件夹中,并且在我的 .csproj 文件中,我将它们嵌入到资源中,如下所示:

<ItemGroup>
<EmbeddedResource Include="Views\**" Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
</ItemGroup>
Run Code Online (Sandbox Code Playgroud)

它们的工作方式与在磁盘上一样,如果我想覆盖/自定义视图,我可以将其复制到本地,并且将自动使用本地视图而不是嵌入视图。