如何在 Razor Pages 中添加对角色的支持和填充角色?
How do I add support for and populate roles in Razor Pages?
我正在尝试了解如何在我的 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 can only be called with a role that derives from IdentityRole.'
谁能看到我在这里遗漏了什么?另外,我真的很想知道如何填充角色。
您可能会将应用程序中的自定义角色(管理员、经理等)与 IdentityUser 混淆。
IdentityUser
是应用程序中用户记录的基本模型。
如果要向用户模型添加自定义属性,请创建一个继承自 IdentityUser
的新 class 并添加新属性。这个新的 class 通常称为 ApplicationUser
,但可以随意命名。
Docs on customizing user model
我推荐学习一个教程。这是来自 Microsoft 文档的一个文档,它经历了许多场景并且也有源代码。
将您的 IdentityUser
更改为 IdentityRole
,如下所示:
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole>() //change this
.AddEntityFrameworkStores<ApplicationDbContext>();
参考:
我正在尝试了解如何在我的 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 can only be called with a role that derives from IdentityRole.'
谁能看到我在这里遗漏了什么?另外,我真的很想知道如何填充角色。
您可能会将应用程序中的自定义角色(管理员、经理等)与 IdentityUser 混淆。
IdentityUser
是应用程序中用户记录的基本模型。
如果要向用户模型添加自定义属性,请创建一个继承自 IdentityUser
的新 class 并添加新属性。这个新的 class 通常称为 ApplicationUser
,但可以随意命名。
Docs on customizing user model
我推荐学习一个教程。这是来自 Microsoft 文档的一个文档,它经历了许多场景并且也有源代码。
将您的 IdentityUser
更改为 IdentityRole
,如下所示:
services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
})
.AddRoles<IdentityRole>() //change this
.AddEntityFrameworkStores<ApplicationDbContext>();
参考: