gpt4 book ai didi

c# - 使用 RoleManager 创建新角色

转载 作者:行者123 更新时间:2023-11-30 22:57:16 24 4
gpt4 key购买 nike

我创建了一个上下文(带有脚手架)和一个用户。我还设置了播放数据库(并创建了一个迁移)。这非常有效!我现在只想创建一个角色,然后将其分配给用户。

为此,我修改了我的 startup.cs 文件以便继续(我找不到说明如何创建/分配具有与 ApplicationDbContext 不同上下文的角色的教程)。

我对代码中的错误很满意(至少我认为是这样),但我不知道如何处理它以及用什么替换对象。

所以我创建了一个 CreateRoles 方法来接收一个 serviceProvider(类型为 IServiceProvider),在这个方法中我尝试初始化 romes,然后将它们分配给我的数据库的不同用户。

我的担忧就在这里(我认为):

var RoleManager = serviceProvider.GetRequiredService > ();

确实,除了我使用 jakformulaireContext 之外,我认为它用于 ApplicationDbContext。

我的问题是:我应该更换什么(如果那是我需要更换的)?

如果您需要模式信息或模式代码,请告诉我!

启动类

公开课启动{ public Startup(IConfiguration配置) { 配置=配置;

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
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<jakformulaireContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("jakformulaireContextConnection")));
services.AddDefaultIdentity<jakformulaireUser>(configg =>
{
configg.SignIn.RequireConfirmedEmail = true;
}).AddEntityFrameworkStores<jakformulaireContext>(); ;


var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingProfile());
});
var mapper = config.CreateMapper();
services.AddSingleton(mapper);

//services.AddAutoMapper();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

services.AddDistributedMemoryCache();

services.AddSession();

// requires
// using Microsoft.AspNetCore.Identity.UI.Services;
// using WebPWrecover.Services;
services.AddSingleton<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);

services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();

app.UseAuthentication();

app.UseCors("CorsPolicy");

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

//CreateRoles(serviceProvider).Wait();
}

private async Task CreateRoles(IServiceProvider serviceProvider)
{
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<jakformulaireUser>>();
string[] roleNames = { "Guest", "Member", "Admin" };
IdentityResult roleResult;

foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}

jakformulaireUser user = await UserManager.FindByEmailAsync("test@test.com");

if (user == null)
{
user = new jakformulaireUser()
{
UserName = "test@test.com",
Email = "test@test.com",
EmailConfirmed = true
};
await UserManager.CreateAsync(user, "Test123$");
}
await UserManager.AddToRoleAsync(user, "Member");


jakformulaireUser user1 = await UserManager.FindByEmailAsync("test@live.be");

if (user1 == null)
{
user1 = new jakformulaireUser()
{
UserName = "test@live.be",
Email = "test@live.be",
EmailConfirmed = true
};
await UserManager.CreateAsync(user1, "Test123$");
}
await UserManager.AddToRoleAsync(user1, "Admin");

}

上下文

public class jakformulaireContext : IdentityDbContext<jakformulaireUser>
{
public jakformulaireContext(DbContextOptions<jakformulaireContext> options)
: base(options)
{

}

protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}

最佳答案

此错误通常在您创建自己的 IdentityRole 时发生或者当您忘记注册 RoleManager 时.

  1. 如果您通过 class jakformulaireContext : IdentityDbContext<YourAppUser, YourIdentityRole> 自定义了上下文, 确保在任何地方使用 RoleManager<IdentityRole>服务已替换为 RoleManager< YourIdentityRole>

  2. 此外,确保 RoleManager<YourIdentityRole>已注册 。如果您不创建自己的 IdentityRole 版本, 只需调用 .AddRoleManager<RoleManager<IdentityRole>>()

     services.AddIdentity<jakformulaireUser, IdentityRole>() 
    .AddRoleManager<RoleManager<IdentityRole>>() // make sure the roleManager has been registered .
    .AddDefaultUI()
    // other features ....
    .AddEntityFrameworkStores<jakformulaireContext>()

关于c# - 使用 RoleManager 创建新角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53782492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com