商店未实现IUserRoleStore< TUser> ASP.NET Core 2.1身份 [英] Store does not implement IUserRoleStore<TUser> ASP.NET Core 2.1 Identity
问题描述
我正在使用ASP.NET Core 2.1身份。我已经覆盖了IdentityUser,因为我需要在用户上添加一些其他属性。
I'm using ASP.NET Core 2.1 Identity. I've overridden IdentityUser because I need to add some additional properties on the user.
在Startup.cs中
In Startup.cs
services.AddDefaultIdentity<PortalUser>().AddEntityFrameworkStores<ApplicationDbContext>();
ApplicationDbContext.cs
ApplicationDbContext.cs
public partial class ApplicationDbContext : IdentityDbContext<PortalUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
PortalUser类
PortalUser class
public class PortalUser : IdentityUser
{
[PersonalData]
public DateTime? LastLoginDateUtc { get; set; }
[PersonalData]
public DateTime? RegistrationDateUtc { get; set; }
}
一切正常。我可以通过添加用户。
That's all working fine. I can add a user via.
_userManager.CreateAsync(user)
但是,当我调用AddToRolesAsync向用户添加角色时,出现了异常。知道为什么吗?
However, when I call AddToRolesAsync to add a role to a user, I'm getting an exception. Any ideas why?
_userManager.AddToRolesAsync(user, new List<string> { roleName });
{System.NotSupportedException: Store does not implement IUserRoleStore<TUser>.
at Microsoft.AspNetCore.Identity.UserManager`1.GetUserRoleStore()
at Microsoft.AspNetCore.Identity.UserManager`1.AddToRolesAsync(TUser user, IEnumerable`1 roles)}
推荐答案
在Startup.cs中,我缺少AddRoles,所以
In Startup.cs, I was missing AddRoles so
services.AddDefaultIdentity<PortalUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
应该是
services.AddDefaultIdentity<PortalUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
注意:顺序很关键。 AddRoles
必须在 AddEntityFrameworkStores
Note: The order is critical. AddRoles
must come before AddEntityFrameworkStores
这篇关于商店未实现IUserRoleStore< TUser> ASP.NET Core 2.1身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!