29

我正在使用 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)}
4

3 回答 3

81

在 Startup.cs 中,我缺少 AddRoles 所以

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

应该

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

注意:顺序很关键。 AddRoles必须先到AddEntityFrameworkStores

于 2018-09-26T18:29:49.023 回答
7

对于asp.net Core 2.2中的解决方案没有任何答案,我想分享我在asp.net Core 2.2中遇到的相同错误

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

并且感谢作者的想法,当我按照asp.net core 2.2中的官方指导(网址在这里:MicrosoftDocs For asp.net core 2.2)时遇到了问题。当我完成他说的步骤并尝试运行该项目时,它会引发异常“Store 未实现 IUserRoleStore”

问题是:实际上,这是 asp.net core 2.1 的示例(我强烈怀疑为什么微软会为用户提供一个没有任何示例代码的文档,这可能没有意义)

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

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

这与您应该在/Program.cs ConfigureService作为步骤中添加的代码相同:在提到的文档中将角色服务添加到身份

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

因此,如果您在 asp.net core 2.2 中遇到同样的问题,另一种解决方案是:

  1. 遵循 asp.net 2.2 中的文档
  2. 当您遇到本章:向身份添加角色服务时,只需忽略官方文档并执行此操作:

替换行

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

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

Areas/Identity/Data/IdentityHostingStartup.cs IdentityHostingStartup::Configure方法中,但没有在 program.cs 中添加(该文件在 asp.net core 2.2 中无法删除)

我使用 Asp.net Identity 的项目稍后将在我的存储库中更新:UWPHelper,祝你好运:)

于 2019-05-27T13:15:20.430 回答
0

我知道作者已经解决了他的问题,但我会为其他完成上述答案中所有步骤但仍然存在此错误的人添加此问题。

来自 Aspnet github

您必须删除Areas/Identity/IdentityHostingStartup.cs中自动生成的 IdentityHostingStartup.Configure 方法

于 2019-03-28T16:36:16.973 回答