当将ASP.NET Core 6项目从使用AddDefaultIdentity切换到AddIdentity时,可能会遇到以下异常:
InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.SignInManager<>' has been registered.
这是由于AddIdentity方法需要手动注册SignInManager服务造成的。以下是
services.AddIdentity
app.UseAuthentication(); app.UseAuthorization();
替换为以下代码:
app.UseRouting();
app.UseAuthentication(); app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
这些更改将确保SignInManager服务在使用AddIdentity方法时正确注册,并且还将确保在使用控制器和视图时进行身份验证和授权。