.NET 8+VS2022脚手架Identity时生成无名用户类问题
解决VS2022 Identity脚手架生成无名称用户类的问题
问题场景
使用VS2022创建.NET 8.0的ASP.NET Core Web应用后,通过Identity脚手架添加ASP.NET Core Identity,指定DbContext名称和自定义用户类名MyApplicationUser,但最终在Area/Identity/Data目录下仅成功生成DbContext类,却出现一个无名称的用户类文件,推测是脚手架代码生成器异常导致。
修复步骤
- 删除无效文件:直接在解决方案资源管理器中找到
Area/Identity/Data下的无名称用户类文件,右键删除。 - 手动创建自定义用户类:在
Area/Identity/Data目录下新建MyApplicationUser.cs文件,代码示例如下:
注意替换代码中的using Microsoft.AspNetCore.Identity; namespace 你的项目命名空间.Area.Identity.Data; public class MyApplicationUser : IdentityUser { // 可按需添加自定义属性 }你的项目命名空间为实际项目的命名空间。 - 关联DbContext与自定义用户类:打开生成的DbContext类(如
ApplicationDbContext.cs),确保其继承自IdentityDbContext<MyApplicationUser>,示例代码:using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace 你的项目命名空间.Area.Identity.Data; public class ApplicationDbContext : IdentityDbContext<MyApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } - 更新Identity服务配置:打开
Program.cs,确保AddIdentity方法指定使用自定义用户类:builder.Services.AddDefaultIdentity<MyApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); - 清理重建项目:右键项目选择「清理」,完成后再选择「重建」,最后运行项目验证功能是否正常。
内容的提问来源于stack exchange,提问作者Manish Kumar
相关产品推荐
相关产品推荐

