如何在ASP.NET Core MVC中重用视图(页面)?
在ASP.NET Core MVC之前,我们将使用RazorGenerator将视图编译为程序集,并通过引入自定义ViewEngine从其他程序集而不是文件系统中加载视图,在其他项目中重用这些视图.
Before ASP.NET Core MVC, we would use RazorGenerator to compile views into assemblies, and we would reuse those views in another project, by introducing a custom ViewEngine that would load the view from the assembly instead of file-system.
在ASP.NET Core MVC中,存在预编译视图的概念,它在2.0版本中是开箱即用的,并创建一个约定为 project_name的程序集.PrecompiledViews.dll .
In ASP.NET Core MVC there is this concept of pre-compiled views and it works out of the box for version 2.0 and creates an assembly that by convention has the name of project_name.PrecompiledViews.dll.
我有两个问题,尽管我在Google上找不到答案.
首先,我不知道如何在另一个项目中重用该DLL.就像我在CompanyBase.dll
中有About.cshtml
页面一样,如何在ProjectAlpha
中重用该页面/视图?
I have two problems though that I can't find an answer for on Google.
First I don't know how to reuse that DLL in another project. Like if I have About.cshtml
page in CompanyBase.dll
, how can I reuse that page/view in ProjectAlpha
?
而且我也不想在发布时进行视图编译.我该如何更改它才能在构建中发生?
And also I don't want view compilation to happen on publish. How can I change it to happen on build?
有一个
应用程序部分是对应用程序资源的抽象,可以从中发现控制器,视图组件或标签助手之类的MVC功能.
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中: Add the following into .csproj (for your library with views) to include views as embedded resources into the dll: 然后将程序集添加为应用程序零件并注册 then add assembly as app part and register the
另一种方法是使用
Another way is to use the
<ItemGroup>
<EmbeddedResource Include="Views\**\*.cshtml" />
</ItemGroup>
ViewComponentFeatureProvider
以进行View发现:ViewComponentFeatureProvider
for View discovery: // 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
. 此SO答案中介绍了这种方法
EmbeddedFileProvider
. This approach is described in this SO answer.