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

。_饼干妹妹 提交于 2019-12-08 21:47:32

There is a Application Parts concept in ASP.NET Core:

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.

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>

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());
             });
}

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

If you want to use views from other assemblies EmbeddedFileProvider has to be used in addition to ViewComponentFeatureProvider.

So the complete ConfigureServices should be something like:

        ...
        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);
        });    

I've had success using views compiled into a dll using the following framework:

https://github.com/ExtCore/ExtCore

The whole framework may not be of use to you but you could certainly analyse the source code to see how that framework achieves it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!