问题描述
我想为SignInManager创建一个自定义类,因此我创建了一个从SignInManager<>
继承的类,如下所示:
I want to create a custom class for my SignInManager, so I've created a class that inherts from SignInManager<>
as follows:
public class ApplicationSignInManager : SignInManager<ApplicationUser>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly ApplicationDbContext _dbContext;
private readonly IHttpContextAccessor _contextAccessor;
public ApplicationSignInManager(
UserManager<ApplicationUser> userManager,
IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory,
IOptions<IdentityOptions> optionsAccessor,
ILogger<SignInManager<ApplicationUser>> logger,
ApplicationDbContext dbContext,
IAuthenticationSchemeProvider schemeProvider
)
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemeProvider)
{
_userManager = userManager ?? throw new ArgumentNullException(nameof(userManager));
_contextAccessor = contextAccessor ?? throw new ArgumentNullException(nameof(contextAccessor));
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
}
}
,然后将其添加到Startup.cs
的服务配置中:
and then I've added it in the services configuration in Startup.cs
:
services.AddDefaultIdentity<ApplicationUser>(configure =>
{
configure.User.AllowedUserNameCharacters += " ";
}).AddSignInManager<ApplicationSignInManager>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();
问题在于默认的SignInManager<ApplicationUser>
无法强制转换为ApplicationSignInManager
,因此当访问其管理器已注入其控制器的页面时,出现此错误:
The problem is that the default SignInManager<ApplicationUser>
cannot be casted to a ApplicationSignInManager
, so I get this error when accessing a page in whose controller the manager is injected:
推荐答案
您的问题是由在.AddDefaultUI(UIFramework.Bootstrap4)
之前注册AddSignInManager<ApplicationSignInManager>()
引起的.
Your issue is caused by that you register AddSignInManager<ApplicationSignInManager>()
before .AddDefaultUI(UIFramework.Bootstrap4)
.
对于 AddDefaultUI ,它将调用 builder.AddSignInManager(); 将会注册typeof(SignInManager<>).MakeGenericType(builder.UserType)
,它将覆盖您之前的设置.
For AddDefaultUI, it will call builder.AddSignInManager(); which will register the typeof(SignInManager<>).MakeGenericType(builder.UserType)
and will override your previous settings.
尝试下面的代码:
services.AddDefaultIdentity<ApplicationUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddSignInManager<ApplicationSignInManager>();
这篇关于在Asp.Net Core 3 Identity中创建自定义SignInManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!