【问题标题】:Blazor - Identity Add roles on application startupBlazor - 身份在应用程序启动时添加角色
【发布时间】:2020-12-06 05:35:34
【问题描述】:

我在 Blazor .net 3.1 中启动了一个应用程序,但遇到了问题。我想在启动应用程序时添加一个具有管理员角色(root)的用户。我正在使用 EF。添加用户有效,但添加角色会引发异常。

System.AggregateException : 'No service for type 'Microsoft.AspNetCore.Identity.RoleManager'1[Microsoft.AspNEtCore.Identity.IdentityRole]' has been registered.ontainer is destroyed)'

我尝试了不同的解决方案,例如ASP.NET Core Identity Add custom user roles on application startupold post,但在 SQLite、SQL Server 上我仍然有同样的异常...

我创建了一个静态类,并在 Startup.cs 中调用了这个方法。

public static class RolesData
{
    private static readonly string[] Roles = new string[] { "Admin", "Manager", "Member" };

    public static async Task SeedRoles(IServiceProvider serviceProvider)
    {
        using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            foreach (var role in Roles)
            {
                if (!await roleManager.RoleExistsAsync(role))
                {
                    await roleManager.CreateAsync(new IdentityRole(role));
                }
            }
        }
    }
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    RolesData.SeedRoles(app.ApplicationServices).Wait();
}

如果您有任何我感兴趣的建议,并且如果您知道一个解释身份验证的网站,我想了解!

感谢您的帮助

【问题讨论】:

  • 分享您的 Statup ConfigureServices 方法

标签: c# asp.net-core blazor


【解决方案1】:

请参阅我的answer,了解如何使用IEntityTypeConfiguration 在 ASP.NET Core(适用于 3.1)中播种各种数据

我还没有在 blazor 上尝试过,但我认为值得一试。

注意:更改需要数据库迁移。

【讨论】:

  • 我开始一个测试项目来测试你的解决方案。
【解决方案2】:

根据错误,您似乎没有配置身份服务器来公开角色。

例如在 Startup.cs 中

services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddRoles<IdentityRole>()  // <------
                .AddEntityFrameworkStores<ApplicationDbContext>();

我有一个标准模板,其中角色为 here

进一步展示了如何启用 Authorize 属性:

@attribute [Authorize(Roles = "Administrator")]

和 AuthorizeView :

<AuthorizeView Roles="Administrator">
    Only Administrators can see this.<br />
</AuthorizeView>
<AuthorizeView Roles="Moderator">
    Only Moderators can see this.<br />
</AuthorizeView>
<AuthorizeView Roles="Moderator,Administrator">
    Administrators and Moderators can see this.
</AuthorizeView>

我对标准项目所做的更改以启用角色并使它们对 Blazor WebAssembly 可见,可以在 commit 中看到

【讨论】:

  • 谢谢!当它起作用时,我喜欢感觉到心脏的那一点点;)
  • 链接断开兄弟! “提交”
  • @LukeVincent 解决了谢谢。这是一个较新的 repo .net 5.0 github.com/BrianLParker/AuthApp/commit/…
  • 非常感谢布莱恩!在你出现之前,我一直在谷歌上搜索这个身份,但成功率为零!现在我的项目可以全速进行了!附言额外的奖励,我的网络应用程序在 net 5.0 中,所以全面获胜。
猜你喜欢
  • 2021-07-20
  • 2017-02-17
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 2019-09-11
相关资源
最近更新 更多