app.UseMigrationsEndPoint()报错解决及ASP.NET Identity移除方法咨询
解决方案
一、修复app.UseMigrationsEndPoint()报错
按顺序排查以下两个常见原因即可解决:
- 调整中间件顺序
你当前的中间件顺序存在错误:自定义404中间件放在最开头会截获系统中间件的请求,且开发环境下UseDeveloperExceptionPage需要放在UseMigrationsEndPoint之前才能正常生效,修改Configure方法的顺序如下:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseMigrationsEndPoint(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } // 自定义404中间件移到此处 app.Use(async (ctx, next) => { await next(); if (ctx.Response.StatusCode == 404 && !ctx.Response.HasStarted) { string originalPath = ctx.Request.Path.Value; ctx.Items["originalPath"] = originalPath; ctx.Request.Path = "/Error/_404"; await next(); } }); // 后续原有中间件保持不变 app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); }
- 修复Identity上下文配置
无法生成迁移文件大概率是UserContext没有正确继承Identity的基类,修改OfflineEventManagment.Data目录下的UserContext.cs代码如下:
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace OfflineEventManagment.Data { public class UserContext : IdentityDbContext<IdentityUser> { public UserContext(DbContextOptions<UserContext> options) : base(options) { } } }
- 手动生成迁移与数据库
修改完成后执行指定上下文的迁移命令即可生成对应数据库:
- 包管理器控制台执行:
Add-Migration InitIdentity -Context UserContext Update-Database -Context UserContext - .NET CLI执行:
dotnet ef migrations add InitIdentity --context UserContext dotnet ef database update --context UserContext
二、移除ASP.NET Identity的步骤
如果不需要登录功能,按以下步骤清理所有相关代码即可:
- 清理服务注册:在
ConfigureServices方法中删除AddDefaultIdentity、AddDbContext<UserContext>两行代码,同时删除UseEndpoints配置里的endpoints.MapRazorPages(); - 清理中间件:在
Configure方法中删除UseMigrationsEndPoint、UseAuthentication、UseAuthorization三个中间件调用 - 清理项目文件:删除项目中
Areas/Identity文件夹、Data/UserContext.cs文件、Migrations目录下的所有迁移文件 - 清理业务代码:删除所有控制器、页面上的
[Authorize]特性,删除所有注入UserManager、SignInManager等Identity服务的逻辑 - 清理配置:删除
appsettings.json中的DefaultConnection数据库连接字符串
三、是否需要新建项目的建议
- 若当前项目已经写了大量业务代码,直接按上述步骤修复报错或者移除Identity即可,无需新建项目
- 若项目刚创建,业务代码量极少,直接新建不带身份验证的ASP.NET Core项目,迁移现有业务代码效率更高,也不会残留冗余配置
内容的提问来源于stack exchange,提问作者Sahil bhatiya
相关产品推荐
相关产品推荐

