Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用RoleManager创建新角色_C#_Asp.net_Asp.net Mvc_Model View Controller_Asp.net Core - Fatal编程技术网

C# 使用RoleManager创建新角色

C# 使用RoleManager创建新角色,c#,asp.net,asp.net-mvc,model-view-controller,asp.net-core,C#,Asp.net,Asp.net Mvc,Model View Controller,Asp.net Core,我创建了一个上下文(使用脚手架)和一个用户。 我还设置了播放db(并创建了一个迁移)。 这很好用! 我现在只想创建一个角色,然后将其分配给一个用户 为此,我修改了startup.cs文件以便继续(我找不到一个教程来演示如何创建/分配一个与ApplicationDbContext不同的上下文的角色) 我对代码中的错误感到满意(至少我认为是这样),但我不知道如何处理它以及用什么替换对象 因此,我创建了一个CreateRoles方法,该方法接收一个serviceProvider(类型为IService

我创建了一个上下文(使用脚手架)和一个用户。 我还设置了播放db(并创建了一个迁移)。 这很好用! 我现在只想创建一个角色,然后将其分配给一个用户

为此,我修改了startup.cs文件以便继续(我找不到一个教程来演示如何创建/分配一个与ApplicationDbContext不同的上下文的角色)

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

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

我担心的是(我认为):

var rolemager=serviceProvider.GetRequiredService>()

事实上,我认为除了使用jakformulaireContext之外,它还用于ApplicationDbContext

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

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

启动类

公营创业 { 公共启动(IConfiguration配置) { 配置=配置; }

公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
配置(选项=>
{
//此lambda确定给定请求是否需要非必要cookie的用户同意。
options.checkApprovered=context=>true;
options.MinimumSameSitePolicy=SameSiteMode.None;
});
services.AddDbContext(选项=>
options.UseSqlServer(
GetConnectionString(“jakformulaireContextConnection”);
services.AddDefaultIdentity(configg=>
{
configg.SignIn.RequireConfirmedEmail=true;
}).AddEntityFrameworkStores();
var config=new AutoMapper.MapperConfiguration(cfg=>
{
AddProfile(新的MappingProfile());
});
var mapper=config.CreateMapper();
服务。AddSingleton(映射器);
//services.AddAutoMapper();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
AddDistributedMemoryCache();
services.AddSession();
//需要
//使用Microsoft.AspNetCore.Identity.UI.Services;
//使用WebPWrecover.Services;
services.AddSingleton();
服务。配置(配置);
services.AddCors(选项=>
{
options.AddPolicy(“CorsPolicy”,
builder=>builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、IServiceProvider服务提供商)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSession();
app.UseAuthentication();
附录UseCors(“公司政策”);
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
//CreateRoles(serviceProvider).Wait();
}
专用异步任务CreateRoles(IServiceProvider服务提供程序)
{
//初始化自定义角色
var rolemager=serviceProvider.GetRequiredService();
var UserManager=serviceProvider.GetRequiredService();
字符串[]roleNames={“来宾”、“成员”、“管理员”};
识别结果角色结果;
foreach(roleName中的变量roleName)
{
var roleExist=wait rolemager.RoleExistsAsync(roleName);
如果(!roleExist)
{
//创建角色并将其植入数据库:问题1
roleResult=await RoleManager.CreateAsync(新的IdentityRole(roleName));
}
}
jakformulaireUser user=await UserManager.FindByEmailAsync(“test@test.com");
if(user==null)
{
user=new-jakformulaireUser()
{
用户名=”test@test.com",
电子邮件=”test@test.com",
emailconfirm=true
};
等待UserManager.CreateAsync(用户,“Test123$”;
}
等待UserManager.AddToRoleAsync(用户,“成员”);
jakformulaireUser user1=等待UserManager.FindByEmailAsync(“test@live.be");
if(user1==null)
{
user1=new-jakformulaireUser()
{
用户名=”test@live.be",
电子邮件=”test@live.be",
emailconfirm=true
};
等待UserManager.CreateAsync(user1,“Test123$”;
}
等待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);
    }
}
公共类jakformulaireContext:IdentityDbContext { 公共jakformulaireContext(DbContextOptions选项) :基本(选项) { } 模型创建时受保护的覆盖无效(ModelBuilder) { 基于模型创建(生成器); //自定义ASP.NET标识模型,并根据需要覆盖默认值。 //例如,可以重命名ASP.NET标识表名称等。 //在调用base.OnModelCreating(builder)后添加自定义项; } }
此错误通常发生在您创建自己的
标识列表
或忘记注册
角色管理器

  • 如果您通过
    类jakformulaireContext:IdentityDbContext
    自定义了上下文,请确保使用
    RoleManager
    服务的任何位置都已替换为
    RoleManagerpublic 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);
        }
    }
    
     services.AddIdentity<jakformulaireUser, IdentityRole>() 
        .AddRoleManager<RoleManager<IdentityRole>>()  // make sure the roleManager has been registered .
        .AddDefaultUI() 
        // other features ....
        .AddEntityFrameworkStores<jakformulaireContext>()