【问题标题】:How do I add support for and populate roles in Razor Pages?如何在 Razor 页面中添加对角色的支持和填充角色?
【发布时间】:2020-06-08 20:59:24
【问题描述】:

我试图弄清楚如何在我的 Razor Pages 应用程序中启用和填充角色。

按照各种教程,Startup.cs 中的ConfigureServices 看起来像这样:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddDefaultIdentity<ApplicationUser>(options =>
        {
            options.SignIn.RequireConfirmedAccount = false;
        })
        .AddRoles<ApplicationUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddRazorPages();

    // Set the default authentication policy to require users to be authenticated
    services.AddControllers(config =>
    {
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });
}

但是对AddDefaultIdentity 的调用会引发异常。

System.InvalidOperationException: 'AddEntityFrameworkStores 只能使用派生自 IdentityRole 的角色调用。'

谁能看到我在这里遗漏了什么?另外,我真的很想知道如何填充角色。

【问题讨论】:

  • 你的问题很相似:stackoverflow.com/a/56466438/12282249
  • @DenisStukalov:我确实看到了那个。但他使用的方法与 Visual Studio 创建的方法不同,我不知道为什么。我找不到关于这些东西的好教程。
  • 应该是 .AddRoles&lt;IdentityRole&gt;() 而不是 IdentityUser。

标签: c# asp.net-core razor-pages asp.net-core-identity


【解决方案1】:

将您的 IdentityUser 更改为 IdentityRole,如下所示:

services.AddDefaultIdentity<ApplicationUser>(options =>
        {
            options.SignIn.RequireConfirmedAccount = false;
        })
        .AddRoles<IdentityRole>()  //change this
        .AddEntityFrameworkStores<ApplicationDbContext>();

参考:

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-3.1#add-role-services-to-identity

【讨论】:

  • 这行得通,谢谢。有填充我的应用程序角色的好例子吗?
  • 嗨@JonathanWood,您对填充您的角色意味着什么?将它们填充到数据库中?请参阅here。或者填充选择列表中的角色?
【解决方案2】:

您可能会将应用程序中的自定义角色(管理员、经理等)与 IdentityUser 混淆。

IdentityUser 是应用程序中用户记录的基本模型。

如果您想向 User 模型添加自定义属性,则创建一个继承自 IdentityUser 的新类并添加新属性。这个新类通常称为ApplicationUser,但可以任意命名。

Docs on customizing user model

我建议遵循一个教程。这是 Microsoft 文档中的一个,它经历了许多场景并且也有源代码。

Official tutorial on authorization and roles

【讨论】:

  • 我以为IdentityUser是应用程序中用户记录的基本模型?
  • 是的,你是对的。我已经更正了答案,谢谢@JonathanWood
猜你喜欢
  • 2019-02-07
  • 2020-11-24
  • 1970-01-01
  • 2018-12-31
  • 2019-03-16
  • 2018-06-18
  • 2018-04-10
  • 2017-07-07
  • 1970-01-01
相关资源
最近更新 更多