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

ASP.NET Core 2.2 MVC中AspNetUsers表不存在问题求助

解决ASP.NET Core 2.2 Identity中"AspNetUsers不存在"的问题

兄弟,我一眼就看出你遇到的核心问题了:你的数据库根本没生成Identity需要的那套表结构,再加上ASP.NET Core和老版MVC 5的配置逻辑不一样,才会找不到你熟悉的那些配置入口。咱们一步步来解决:

1. 先把数据库连接字符串配置规范化(换掉硬编码)

ASP.NET Core已经不用web.config了,所有配置都放在appsettings.json里,你现在的配置文件里连连接字符串节点都没有,Startup里硬写的连接字符串既不规范也容易出错。先修改appsettings.json,补上连接字符串:

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "XmlViewerContext": "Data Source = (localdb)\\ProjectsV13; Initial Catalog = XmlViewer; Integrated Security = True; Connect Timeout = 30;"
  }
}

2. 修正Startup.cs里的服务注册顺序和配置

你现在的Startup里先注册了Identity服务,再注册DbContext,这会导致Identity找不到依赖的DbContext。同时要改成从配置文件读取连接字符串,不要硬编码。修改ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    // 先注册DbContext,再注册Identity(依赖顺序不能反)
    services.AddDbContext<XmlViewerContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("XmlViewerContext")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<XmlViewerContext>()
        .AddDefaultTokenProviders();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

3. 执行EF迁移生成数据库表

这是最关键的一步!你现在的XmlViewer数据库里根本没有AspNetUsers、AspNetRoles这些Identity必备的表,所以注册时才会报错。咱们用EF Core的迁移功能自动生成这些表:

方法一:用VS的包管理器控制台

  1. 打开VS顶部菜单:工具 -> NuGet包管理器 -> 包管理器控制台
  2. 执行初始化迁移命令:
Add-Migration InitialCreate
  1. 把迁移应用到数据库:
Update-Database

方法二:用.NET CLI命令

打开命令行,切换到项目根目录(有.csproj文件的目录),执行:

dotnet ef migrations add InitialCreate
dotnet ef database update

执行完这两步,你的XmlViewer数据库里就会自动生成所有Identity需要的表了。

4. 额外小提示

  • 为什么找不到Server Explorer里的DefaultConnection?ASP.NET Core不会自动把连接字符串加到Server Explorer里,等迁移完成数据库创建好后,你可以手动在Server Explorer里添加这个连接(选择(localdb)\ProjectsV13,再选中XmlViewer数据库)。
  • 你AccountController里的Login方法重复加了[HttpGet],虽然不影响功能,但可以删掉一个让代码更整洁。

这样操作完,再测试注册功能,应该就不会报"AspNetUsers不存在"的错误了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:04:11