如何为Mac上CLI创建的无Identity的ASP.NET Core MVC项目添加Identity?
给现有ASP.NET Core MVC项目添加Identity功能(CLI方式)
当然有更优的方案!不用重新创建项目,完全可以通过dotnet CLI命令给你已有的MVC项目注入Identity功能,步骤清晰且高效:
1. 进入项目目录并添加Identity依赖包
打开终端,切换到你的ASP.NET Core MVC项目根目录,执行以下命令添加Identity的核心依赖和UI组件:
dotnet add package Microsoft.AspNetCore.Identity.UI # 根据你使用的数据库替换对应包,比如Sqlite/PostgreSQL等 dotnet add package Microsoft.EntityFrameworkCore.SqlServer
2. Scaffold Identity到现有项目
使用dotnet new identity命令直接将Identity的登录、注册等UI页面、服务配置生成到你的项目中,关键参数说明:
--use-existing-db:指定使用项目中已有的数据库上下文,避免创建新的DbContext--force:如果项目中已有部分Identity相关文件,强制覆盖(按需选择)
执行命令:
dotnet new identity --use-existing-db --force
3. 调整数据库上下文
打开项目中的数据库上下文类(通常是ApplicationDbContext.cs),修改继承关系,让它兼容Identity的实体存储:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; public class ApplicationDbContext : IdentityDbContext<IdentityUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } // 保留你原有的DbSet定义... }
4. 配置Identity服务和中间件
根据你的.NET版本,在项目启动文件中完成Identity的配置:
.NET 6+(Program.cs)
在builder.Services.AddControllersWithViews();之后添加Identity服务:
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>();
然后在app.UseAuthorization();之前添加认证中间件:
app.UseAuthentication();
.NET 5及更早(Startup.cs)
在ConfigureServices方法中添加:
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>();
在Configure方法的app.UseAuthorization();之前添加:
app.UseAuthentication();
5. 同步数据库结构
最后通过EF Core CLI命令将Identity的表结构同步到你的数据库:
dotnet ef migrations add AddIdentitySchema dotnet ef database update
完成这些步骤后,你的现有MVC项目就已经集成了完整的Identity功能,包含登录、注册、密码重置等默认UI和认证授权逻辑。
内容的提问来源于stack exchange,提问作者Anil P Babu
相关产品推荐
相关产品推荐

