问题描述
我在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 startup,old 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();
}
如果您有任何我感兴趣的建议,并且还知道一个解释身份验证的网站,我想理解!
感谢您的帮助
解决方法
有关使用IEntityTypeConfiguration
在ASP.NET Core(适用于3.1)中播种各种数据的信息,请参见我的answer
我还没有尝试过使用blazor,但我认为值得尝试。
注意:更改需要数据库迁移。
,由于出现错误,您尚未将身份服务器配置为公开角色。
例如在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
中看到