You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Razor视图引擎从其他项目加载视图(垂直切片架构场景)

解决Razor视图引擎无法识别其他项目中视图的问题

1. 安装必要NuGet包

在Core项目中安装Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation包,这是让Razor支持编译并查找非启动项目视图的基础依赖。

2. 配置视图文件复制属性

找到Core项目中所有.cshtml视图文件,右键选择「属性」,将「复制到输出目录」设置为如果较新则复制或始终复制。确保视图文件能被复制到程序运行目录,让视图引擎可访问。

3. 修改Web项目服务配置

在Web项目的Program.cs中,更新AddControllersWithViews的配置,添加运行时编译支持并指定Core项目的物理路径,让视图引擎扫描该项目下的视图:

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews()
    .AddApplicationPart(typeof(Faction).Assembly)
    .AddRazorRuntimeCompilation(options =>
    {
        // 替换为你的Core项目实际路径
        var coreProjectRoot = Path.Combine(Directory.GetCurrentDirectory(), "../YourCoreProjectName");
        options.FileProviders.Add(new PhysicalFileProvider(coreProjectRoot));
    });

4. 验证视图路径一致性

确保调用视图时的路径与Core项目中视图的实际结构完全匹配。比如你当前的调用:

return View("/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml", viewModel);

需要对应Core项目根目录下的Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml文件结构。

补充:自定义视图位置扩展(可选)

如果需要更灵活的视图查找规则,可实现IViewLocationExpander接口自定义视图位置:

public class CoreProjectViewLocationExpander : IViewLocationExpander
{
    public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
    {
        // 添加Core项目的视图位置模板
        var coreLocations = new[]
        {
            "/Features/{1}/{0}.cshtml",
            "/Features/{0}.cshtml"
        };
        return coreLocations.Concat(viewLocations);
    }

    public void PopulateValues(ViewLocationExpanderContext context)
    {
        // 无需额外参数,留空即可
    }
}

随后在Program.cs中注册该扩展:

builder.Services.AddControllersWithViews()
    .AddApplicationPart(typeof(Faction).Assembly)
    .AddRazorOptions(options =>
    {
        options.ViewLocationExpanders.Add(new CoreProjectViewLocationExpander());
    })
    .AddRazorRuntimeCompilation(options =>
    {
        var coreProjectRoot = Path.Combine(Directory.GetCurrentDirectory(), "../YourCoreProjectName");
        options.FileProviders.Add(new PhysicalFileProvider(coreProjectRoot));
    });

配置完成后,你可以用更简洁的方式调用视图,比如return View("GetLast5GamesStatsGlobal", viewModel);,视图引擎会自动在Core项目的对应路径中查找。

内容的提问来源于stack exchange,提问作者bookuhah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:03:02