C# 如何让razor从模板服务中的另一个程序集中查找视图

C# 如何让razor从模板服务中的另一个程序集中查找视图,c#,razor,.net-core,asp.net-core-2.1,asp.net-mvc-areas,C#,Razor,.net Core,Asp.net Core 2.1,Asp.net Mvc Areas,我正在尝试从另一个项目加载razor视图。我已经下了几个不同的兔子洞,但到目前为止,我还没有找到一个办法使这项工作。然而,从我的研究来看,似乎有两种主要的方法可以让这项工作起作用 一种选择是使用嵌入式资源,然后将嵌入式文件提供程序连接到razor中。我可能错了,但我认为这是一种.NETCore2.1之前的方法。我的理解是,在2.1版本中,Razor视图是在构建时编译的。将其设置为嵌入式将保存实际文件,这对于较旧的运行时编译非常有用 // Add the embedded file provide

我正在尝试从另一个项目加载razor视图。我已经下了几个不同的兔子洞,但到目前为止,我还没有找到一个办法使这项工作。然而,从我的研究来看,似乎有两种主要的方法可以让这项工作起作用

一种选择是使用嵌入式资源,然后将嵌入式文件提供程序连接到razor中。我可能错了,但我认为这是一种.NETCore2.1之前的方法。我的理解是,在2.1版本中,Razor视图是在构建时编译的。将其设置为嵌入式将保存实际文件,这对于较旧的运行时编译非常有用

// Add the embedded file provider to be used with razor view templates
var viewAssembly = typeof(CoreStartup).GetTypeInfo().Assembly;
var fileProvider = new EmbeddedFileProvider(viewAssembly);
services.Configure<RazorViewEngineOptions>(o => o.FileProviders.Add(fileProvider));
services.AddTransient<ITemplateService, TemplateService>();
现在我正在尝试获取EmailDetails.cshtml共享视图

/Areas
    /Common
        /Views
            /Shared
                -EmailDetails.cshtml

您可以使用IViewLocationExpander。请参见检查此项 这仅适用于在应用程序目录中搜索视图:

public class MyViewLocationExpander : IViewLocationExpander
{

    public void PopulateValues(ViewLocationExpanderContext context)
    {

    }

    public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(f => f.Replace("/Views/", "/Areas/Common/Views/")); 
    }

}
公共类MyViewLocationExpander:IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext上下文)
{
}
公共虚拟IEnumerable ExpandViewLocations(ViewLocationExpanderContext上下文,IEnumerable viewLocations)
{
返回视图位置。选择(f=>f.Replace(“/Views/”,“/Areas/Common/Views/”);
}
}
在创业课程中:

services.Configure<RazorViewEngineOptions>(options =>
        {                
            options.ViewLocationExpanders.Add( new MyViewLocationExpander());                
        });
services.Configure(选项=>
{                
options.ViewLocationExpanders.Add(新的MyViewLocationExpander());
});

如果您需要从应用程序的“外部”查看负载,请选中此项:

如果链接断开,请展开此答案以显示解决方案。我将此标记为答案,但我不再能够访问有问题的回购来测试它。
public class MyViewLocationExpander : IViewLocationExpander
{

    public void PopulateValues(ViewLocationExpanderContext context)
    {

    }

    public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        return viewLocations.Select(f => f.Replace("/Views/", "/Areas/Common/Views/")); 
    }

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