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

VS2019新建ASP.NET Core 5.0 MVC项目.cshtml报错但运行正常如何解决

问题描述

使用C#创建全新的ASP.NET Core 5.0 MVC项目后,打开任意默认.cshtml页面时,错误列表窗口会提示多个错误,但项目依然可以正常生成和运行,常见错误包括:

  • The name 'ViewData' does not exist in the current context
  • The name 'RenderBody' does not exist in the current context
  • The name 'await' does not exist in the current context
  • The name 'Context' does not exist in the current context
  • The namespace "ASP" already contains a definition for '_Page_Default_cshtml'
解决方案
  • 清理Visual Studio和项目缓存
    关闭所有Visual Studio窗口,删除以下路径的缓存文件:

    1. Visual Studio组件缓存:%LocalAppData%\Microsoft\VisualStudio\<对应VS版本号文件夹>\ComponentModelCache
    2. 项目本地缓存:删除项目根目录下的.vs、bin、obj三个文件夹
      完成后重新打开Visual Studio加载项目,等待IntelliSense重新索引即可。
  • 检查_ViewImports.cshtml配置
    确认项目Views目录下存在_ViewImports.cshtml文件,且包含正确的命名空间导入和标签助手声明,示例配置如下:

@using 你的项目实际命名空间
@using 你的项目实际命名空间.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

如果文件缺失或配置错误,补上对应内容后重新保存项目即可。

  • 调整错误列表过滤规则
    这类报错大多是Visual Studio IntelliSense的临时识别异常,不影响实际项目编译。你可以将错误列表顶部的过滤选项从Build + IntelliSense切换为Build Only,即可直接过滤掉这类无效的智能提示错误。

  • 修复Razor重复编译冲突
    针对命名空间重复定义的错误,你可以修改项目根目录下的.csproj项目文件,添加以下配置避免本地编译时重复生成Razor视图代码:

<PropertyGroup>
  <!-- 本地构建时不预编译Razor视图 -->
  <RazorCompileOnBuild>false</RazorCompileOnBuild>
  <!-- 发布时仍预编译Razor视图保证性能 -->
  <RazorCompileOnPublish>true</RazorCompileOnPublish>
</PropertyGroup>

保存项目文件后重新生成即可解决冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 01:48:04