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

配置RazorViewEngineOptions自定义视图路径失效,为何仍搜默认位置?

问题:配置RazorViewEngineOptions自定义视图路径无效

配置代码

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();
    services.AddRazorPages();
    services.AddDbContext<ProductDbContext>(opts =>
    {
        opts.UseSqlServer(Configuration["ConnectionStrings:AppDataConnection"]);
    });
    services.AddHttpsRedirection(opts =>
    {
        opts.HttpsPort = 44350;
    });      
    services.Configure<RazorViewEngineOptions>(opts => {
        opts.PageViewLocationFormats.Clear();
        opts.PageViewLocationFormats.Add("/Pages/Shared/Layouts/{0}" + RazorViewEngine.ViewExtension);              
    });
}

问题描述

尝试配置RazorViewEngineOptions,清空PageViewLocationFormats集合并添加自定义视图路径,但程序仍仅搜索默认视图位置,抛出InvalidOperationException异常,提示无法找到_Layout视图,搜索路径为/Views/Home/_Layout.cshtml、/Views/Shared/_Layout.cshtml、/Pages/Shared/_Layout.cshtml。此前旧版本中相同操作可正常生效,询问当前配置为何无效。


解决方案
  • 核心原因:ASP.NET Core 3.0及以上版本中,Razor Pages与MVC的视图引擎配置被拆分,RazorViewEngineOptions仅针对MVC视图(/Views目录下的文件),而Razor Pages的视图路径配置需要使用RazorPagesOptions。

  • 针对Razor Pages的正确配置方式:
    修改AddRazorPages的配置,直接在其中设置页面视图位置:

    services.AddRazorPages(options =>
    {
        // 清空默认路径
        options.PageViewLocationFormats.Clear();
        // 添加自定义布局路径
        options.PageViewLocationFormats.Add("/Pages/Shared/Layouts/{0}" + RazorViewEngine.ViewExtension);
    });
    
  • 同时支持MVC与Razor Pages的配置:
    如果项目同时使用MVC视图和Razor Pages,需要分别配置两种选项:

    // 配置MVC视图的路径
    services.Configure<RazorViewEngineOptions>(opts => {
        opts.ViewLocationFormats.Clear();
        opts.ViewLocationFormats.Add("/Views/Custom/{0}" + RazorViewEngine.ViewExtension);
    });
    
    // 配置Razor Pages的路径
    services.AddRazorPages(options =>
    {
        options.PageViewLocationFormats.Clear();
        options.PageViewLocationFormats.Add("/Pages/Shared/Layouts/{0}" + RazorViewEngine.ViewExtension);
    });
    
  • 额外检查项:

    • 确认自定义路径下的_Layout.cshtml文件存在,路径完全匹配(区分大小写);
    • 确认Razor页面中布局引用的名称正确(如Layout = "_Layout";)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 16:13:11