如何在ASP.NET Core 2.1中使用角色? [英] How to use Roles in ASP.NET Core 2.1?
问题描述
我使用以下方法创建了一个测试项目:
I've created a test project using:
dotnet new razor --auth Individual --output Test
这将创建一个Startup.cs,其中包含:
This creates a Startup.cs that contains:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
我想播种一些用户和角色.用户和角色都将使用相同的存储(SQLite).我正在使用静态类作为种子,从 Program
调用它.
I want to seed some users and roles. Both users and roles will use the same store (SQLite). I'm using a static class for seeding which it's called from Program
.
我可以为用户提供种子,但不能为角色提供种子,因为上述内容似乎并未注入 RoleManager
.
I can seed users, but not roles, since the above does not seem to inject a RoleManager
.
在ASP.NET Core 2.0中,使用以下内容:
In ASP.NET Core 2.0 the following is used:
services.AddIdentity<IdentityUser, IdentityRole>()
我猜想 AddDefaultIdentity
在2.1中是新功能,但问题是它没有注入 RoleMnager
,所以我该怎么办?
I'm guessing AddDefaultIdentity
is new in 2.1 but the problem is that it does not inject a RoleMnager
, so what should I do?
推荐答案
看来,最终Microsoft明白并不是每个应用程序都需要角色并将它们分开.
It seems that finally Microsoft understood that not every application needs roles and separated them.
请注意, AddDefaultIdentity
声明为:
public static IdentityBuilder AddDefaultIdentity<TUser>(this IServiceCollection services) where TUser : class;
因此,您可以继续通过该 IdentityBuilder
配置身份"选项.您想做的是:
So, you can continue to configure Identity options through that IdentityBuilder
. What you want to do is:
services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>();
幸运的是,他们还删除了 IUser
和 IRole
约束,因此现在您可以在完全独立的程序集中使用模型,而不必安装数百个NuGet软件包.
Fortunately, they also removed the IUser
and IRole
constrains, so now you can use models in a completely separate assembly without having to install hundreds of NuGet packages.
这篇关于如何在ASP.NET Core 2.1中使用角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!