如何在 ASP.NET 核心 MVC 中重用视图(页面)?

How to reuse views (pages) in ASP.NET Core MVC?

在 ASP.NET Core MVC 之前,我们会使用 RazorGenerator 将视图编译成程序集,然后我们会在另一个项目中重用这些视图,方法是引入一个自定义 ViewEngine,它会从程序集而不是文件中加载视图-系统。

在 ASP.NET 核心 MVC 中有这个概念 预编译视图 并且它在 2.0 版中开箱即用,并创建一个按照惯例具有的程序集project_name.PrecompiledViews.dll.

的名字

我有两个问题无法在 Google 上找到答案。 首先,我不知道如何在另一个项目中重用该 DLL。就像我在 CompanyBase.dll 中有 About.cshtml 页面一样,我如何在 ProjectAlpha 中重用 page/view?

而且我也不希望在发布时进行视图编译。我怎样才能将其更改为在构建时发生?

ASP.NET核心有一个Application Parts概念:

An Application Part is an abstraction over the resources of an application, from which MVC features like controllers, view components, or tag helpers may be discovered.

将以下内容添加到 .csproj(用于包含视图的库)以将视图作为嵌入资源包含到 dll 中:

<ItemGroup>
   <EmbeddedResource Include="Views\**\*.cshtml" /> 
</ItemGroup>

然后将程序集添加为应用程序部件并为视图发现注册 ViewComponentFeatureProvider

// using System.Reflection;
// using Microsoft.AspNetCore.Mvc.ApplicationParts;
// using Microsoft.AspNetCore.Mvc.ViewComponents;

public void ConfigureServices(IServiceCollection services)
{
     ...
     var assembly = typeof(ClassInYourLibrary).GetTypeInfo().Assembly;
     var part = new AssemblyPart(assembly);

     services.AddMvc()
             .ConfigureApplicationPartManager(p => {
                p.ApplicationParts.Add(part);
                p.FeatureProviders.Add(new ViewComponentFeatureProvider());
             });
}

另一种方法是使用EmbeddedFileProvider.

中描述了这种方法

如果你想使用来自其他程序集的视图,除了ViewComponentFeatureProvider 之外,还必须使用EmbeddedFileProvider。

所以完整的 ConfigureServices 应该是这样的:

        ...
        var assembly = typeof( Iramon.Web.Common.ViewComponents.ActiveAccountViewComponent).GetTypeInfo().Assembly;
        var part = new AssemblyPart(assembly);

        services.AddMvc()
            .ConfigureApplicationPartManager(p => {                    
                p.ApplicationParts.Add(part);
                p.FeatureProviders.Add(new ViewComponentFeatureProvider());                    
            });        

        var embeddedFileProvider = new EmbeddedFileProvider(
            assembly
        );

        //Add the file provider to the Razor view engine
        services.Configure<RazorViewEngineOptions>(options =>
        {                
            options.FileProviders.Add(embeddedFileProvider);
        });    

我已经成功地使用了使用以下框架编译成 dll 的视图:

https://github.com/ExtCore/ExtCore

整个框架可能对您没有用,但您当然可以分析源代码以了解该框架是如何实现的。