gpt4 book ai didi

c# - Store 没有实现 IUserRoleStore ASP.NET Core Identity

转载 作者:太空狗 更新时间:2023-10-29 17:30:01 27 4
gpt4 key购买 nike

我正在使用 ASP.NET Core 2.1 身份。我已经覆盖了 IdentityUser,因为我需要为用户添加一些额外的属性。

在 Startup.cs 中

services.AddDefaultIdentity<PortalUser>().AddEntityFrameworkStores<ApplicationDbContext>();

ApplicationDbContext.cs

public partial class ApplicationDbContext : IdentityDbContext<PortalUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{

}
}

PortalUser 类

public class PortalUser : IdentityUser
{
[PersonalData]
public DateTime? LastLoginDateUtc { get; set; }

[PersonalData]
public DateTime? RegistrationDateUtc { get; set; }
}

一切正常。我可以通过添加用户。

_userManager.CreateAsync(user)

但是,当我调用 AddToRolesAsync 为用户添加角色时,出现异常。有什么想法吗?

_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

services.AddDefaultIdentity<PortalUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();

应该是

services.AddDefaultIdentity<PortalUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();

注意:顺序很重要。 AddRoles 必须在 AddEntityFrameworkStores

之前

关于c# - Store 没有实现 IUserRoleStore<TUser> ASP.NET Core Identity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52522248/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com