本文介绍了Store 没有实现 IUserRoleStore<TUser>ASP.NET 核心标识的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 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

这篇关于Store 没有实现 IUserRoleStore&lt;TUser&gt;ASP.NET 核心标识的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 20:06