商店未实现IUserRoleStore< TUser>ASP.NET核心身份 [英] Store does not implement IUserRoleStore<TUser> ASP.NET Core Identity

查看:30
本文介绍了商店未实现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

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆