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

为何Razor Page出现CS0246错误?添加using语句仍无效

解决Razor Page中CS0246类型找不到错误

我在Razor Page开发中遇到了CS0246错误(找不到类型或命名空间名称“ContatoModel”),已经尝试在代码中添加using ContatoModel;语句,但问题依然存在,希望能解决这个错误,让项目正常构建运行。

错误相关信息

错误截图显示CS0246编译错误,提示无法找到ContatoModel类型。

自动生成的Razor编译代码如下:

#pragma checksum "C:\Users\Nathan\Documents\ASPNET PJ\Views\Contato\Criar.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "0419d52b5c6c647b8ba18e9d7de1b5045cdb5bb3"
// <auto-generated/>
#pragma warning disable 1591
[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Contato_Criar), @"mvc.1.0.view", @"/Views/Contato/Criar.cshtml")]
namespace AspNetCore
{
    #line hidden
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using Microsoft.AspNetCore.Mvc.ViewFeatures;
    using ContatoModel;
#nullable restore
#line 1 "C:\Users\Nathan\Documents\ASPNET PJ\Views\_ViewImports.cshtml"
using ASPNET_PJ;

#line default
#line hidden
#nullable disable
#nullable restore
#line 2 "C:\Users\Nathan\Documents\ASPNET PJ\Views\_ViewImports.cshtml"
using ASPNET_PJ.Models;

#line default
#line hidden
#nullable disable
    [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"0419d52b5c6c647b8ba18e9d7de1b5045cdb5bb3", @"/Views/Contato/Criar.cshtml")]
    [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"30bddb7a998eb7023ecaaf3235c8530011feaaed", @"/Views/_ViewImports.cshtml")]
    #nullable restore
    public class Views_Contato_Criar : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<ContatoModel>
    #nullable disable
   

排查与解决步骤

  • 确认ContatoModel的命名空间:检查你的ContatoModel类文件,看它的命名空间是否为ContatoModel,还是属于ASPNET_PJ.Models这类已导入的命名空间。如果是后者,无需单独添加using ContatoModel;,反而要确保视图里的模型引用对应正确命名空间。
  • 检查项目引用:如果ContatoModel类在单独的类库项目中,右键当前Web项目→添加→项目引用,勾选包含该模型的类库。
  • 清理重建项目:
    1. 右键解决方案→清理解决方案
    2. 删除项目目录下的bin和obj文件夹
    3. 右键解决方案→重建解决方案
  • 修正视图模型声明:在Criar.cshtml顶部,将模型声明改为@model 正确命名空间.ContatoModel,例如如果类在ASPNET_PJ.Models下,就写@model ASPNET_PJ.Models.ContatoModel。
  • 检查_ViewImports.cshtml:确认文件中导入的命名空间覆盖了你的模型类,比如@using ASPNET_PJ.Models已经存在的话,视图中可以直接使用ContatoModel而无需额外using。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:55:40