Store 没有实现 IUserRoleStore<TUser> ASP.NET Core Identity

Store does not implement IUserRoleStore<TUser> ASP.NET Core Identity

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

在Startup.cs

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

ApplicationDbContext.cs

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

    }
}

门户用户class

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

之前

我知道作者已经解决了他的问题,但我会为所有执行了上述答案中的所有步骤但仍然出现此错误的人添加这个。

来自 Aspnet github

您必须删除 Areas/Identity/IdentityHostingStartup.cs

中自动生成的 IdentityHostingStartup.Configure 方法

由于asp.net Core 2.2中的解决方案没有任何答案,我想分享我在[中遇到的相同错误=72=]核心2.2

首先,这里是针对asp.net core 2.1中相同错误的另一种解决方案 https://github.com/aspnet/AspNetCore.Docs/issues/8683

多亏作者的思路,我按照asp.net core 2.2中的官方指导遇到了问题(url在这里: MicrosoftDocs For asp.net core 2.2)。当我完成他说的步骤并尝试 运行 项目时,它会抛出异常 "Store does not implement IUserRoleStore"

问题是:实际上,这是 asp.net 核心 2.1 的示例(而且我强烈怀疑为什么 Microsoft 会向用户提供没有任何示例代码的文档,这没有意义可能)

你会发现,在Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure方法中你有以下代码:

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

这与您应该在 /Program.cs ConfigureService 中添加的代码相同,作为步骤:Add Role services to Identity 在提到的文档中:

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

所以如果你在 asp.net 核心 2.2 中遇到同样的问题,另一种解决方案是:

  1. 遵循 asp.net 2.2
  2. 中的文档
  3. 当你遇到这一章:向身份添加角色服务时,请忽略官方文档并执行:

替换行

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

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

Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure方法中,但不在program.cs中添加(文件不能在asp.net核心2.2)

我使用的项目Asp.net身份稍后会在我的仓库中更新:UWPHelper,祝你好运:)