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

ASP.NET Core MVC修改视图目录路径后无法加载视图的问题

解决ASP.NET Core MVC自定义视图目录无法加载及VS识别问题

问题原因

ASP.NET Core MVC默认仅在根目录的/Views、/Pages目录搜索视图;同时Visual Studio的视图创建功能依赖项目文件对视图目录的标记,未配置时无法识别自定义Web/Views目录。

解决方案

1. 配置视图引擎搜索路径

在Program.cs中扩展Razor视图的位置格式,让框架能找到Web/Views下的视图:

var builder = WebApplication.CreateBuilder(args);

// 添加控制器和视图服务
builder.Services.AddControllersWithViews()
    .AddRazorOptions(options =>
    {
        // 添加自定义视图路径,顺序代表搜索优先级
        options.ViewLocationFormats.Add("/Web/Views/{1}/{0}.cshtml"); // {1}=控制器名,{0}=视图名
        options.ViewLocationFormats.Add("/Web/Views/Shared/{0}.cshtml"); // 共享视图路径
    });

var app = builder.Build();

// 其他中间件配置...

app.Run();

2. 让Visual Studio识别自定义视图目录

编辑项目文件(.csproj),添加以下配置,标记Web/Views下的文件为视图内容,恢复右键添加视图功能:

<ItemGroup>
  <!-- 标记视图文件 -->
  <Content Include="Web\Views\**\*.cshtml" />
  <!-- 若使用代码后置文件,添加此节点 -->
  <Content Include="Web\Views\**\*.cshtml.cs" Condition="Exists('Web\Views\**\*.cshtml.cs')" />
  <!-- 确保目录在解决方案资源管理器中正确显示 -->
  <Folder Include="Web\Views\" />
</ItemGroup>

验证

修改完成后重新生成项目,视图即可正常加载,右键点击控制器时也会显示“添加视图”选项。

原报错信息:

InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Main/Index.cshtml
/Views/Shared/Index.cshtml
/Pages/Shared/Index.cshtml

Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable<string> originalLocations)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:26:04