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

为此,我修改了startup.cs文件以继续进行操作(我找不到能够显示如何使用不同于ApplicationDbContext的上下文创建/分配角色的教程)。

我对代码中的错误感到满意(至少在我看来),但我不知道如何处理该错误以及如何替换该对象。

因此,我创建了一个CreateRoles方法,该方法接收一个serviceProvider(类型为IServiceProvider),并且在此方法中,我尝试初始化rome,然后将它们分配给数据库的其他用户。

我的关注在这里(我认为):


  var RoleManager = serviceProvider.GetRequiredService>();


实际上,除了使用jakformulaireContext外,我认为它用于ApplicationDbContext。

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

让我知道您是否需要模式信息或模式代码!

启动班

公共类创业
{
    公共启动(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("[email protected]");

    if (user == null)
    {
        user = new jakformulaireUser()
        {
            UserName = "[email protected]",
            Email = "[email protected]",
            EmailConfirmed = true
        };
        await UserManager.CreateAsync(user, "Test123$");
    }
    await UserManager.AddToRoleAsync(user, "Member");


    jakformulaireUser user1 = await UserManager.FindByEmailAsync("[email protected]");

    if (user1 == null)
    {
        user1 = new jakformulaireUser()
        {
            UserName = "[email protected]",
            Email = "[email protected]",
            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时,通常会发生此错误。


如果您已通过class jakformulaireContext : IdentityDbContext<YourAppUser, YourIdentityRole>自定义上下文,请确保使用RoleManager<IdentityRole>服务的任何地方均已替换为RoleManager< YourIdentityRole>
另外,请确保已注册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/

10-11 02:24