我正在嘗試為我的應用程式構建一個授權系統(基于角色的授權)。
我有種子角色類,但我不知道Program.cs每次當應用程式像以下代碼一樣運行時呼叫種子方法的正確方法:
using login_and_registration.Areas.Identity.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace login_and_registration.Models
{
public class SeedRoles
{
public static void Initialize(IServiceProvider serviceProvider)
{
var context = serviceProvider.GetService<lAppregistrationContext>();
string[] roles = new string[] { "Owner", "Administrator", "Tests2", "Editor", "Buyer", "Business", "Seller", "Subscriber" };
foreach (string role in roles)
{
var roleStore = new RoleStore<IdentityRole>(context);
if (!context.Roles.Any(r => r.Name == role))
{
roleStore.CreateAsync(new IdentityRole(role));
}
}
context.SaveChangesAsync();
}
}
}
uj5u.com熱心網友回復:
該類SeedRoles應該是一個靜態類,你可以修改它如下:
//required
//using Microsoft.AspNetCore.Identity;
//using Microsoft.EntityFrameworkCore;
public static class SeedRoles
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new ApplicationDbContext(serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
string[] roles = new string[] { "Owner", "Administrator", "Tests2", "Editor", "Buyer", "Business", "Seller", "Subscriber" };
var newrolelist = new List<IdentityRole>();
foreach (string role in roles)
{
if (!context.Roles.Any(r => r.Name == role))
{
newrolelist.Add(new IdentityRole(role));
}
}
context.Roles.AddRange(newrolelist);
context.SaveChanges();
}
}
}
注意:在我的應用程式中,資料庫背景關系是ApplicationDbContext,您可以將其更改為您的。
然后,在program.cs檔案中,可以在該var app = builder.Build();行后面呼叫種子角色方法,代碼如下:
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //enable Identity Role
.AddEntityFrameworkStores<ApplicationDbContext>() ;
builder.Services.AddControllersWithViews();
var app = builder.Build();
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
SeedRoles.Initialize(services);
}
結果如下:

更多詳細資訊,您可以查看官方檔案和示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/410255.html
標籤:
