如何在ASP.NET Core MVC中重用视图(页面)? [英] How to reuse views (pages) in ASP.NET Core MVC?

查看:250
本文介绍了如何在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:

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

然后将程序集添加为应用程序零件并注册ViewComponentFeatureProvider以进行View发现:

then add assembly as app part and register the 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答案中介绍了这种方法


Another way is to use the EmbeddedFileProvider. This approach is described in this SO answer.

这篇关于如何在ASP.NET Core MVC中重用视图(页面)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆