Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.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# ';不为类型'提供服务;Identity.UserManager`1[ProjectName.ApplicationUser]';已注册。当容器被销毁时可注册)和#x27;_C#_Asp.net Core_Authentication_Identity_Roles - Fatal编程技术网

C# ';不为类型'提供服务;Identity.UserManager`1[ProjectName.ApplicationUser]';已注册。当容器被销毁时可注册)和#x27;

C# ';不为类型'提供服务;Identity.UserManager`1[ProjectName.ApplicationUser]';已注册。当容器被销毁时可注册)和#x27;,c#,asp.net-core,authentication,identity,roles,C#,Asp.net Core,Authentication,Identity,Roles,我正在尝试向我的项目添加一些角色和用户。我使用的是ASP.NET核心版本3.1。现在,我在我的创业课程中尝试了这一点: private async Task CreateRoles(IServiceProvider serviceProvider) { //initializing custom roles var RoleManager = serviceProvider.GetRequiredService<RoleM

我正在尝试向我的项目添加一些角色和用户。我使用的是ASP.NET核心版本3.1。现在,我在我的创业课程中尝试了这一点:

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

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

        // find the user with the admin email 
        var _user = await UserManager.FindByEmailAsync("admin@gmail.com");

        // check if the user exists
        if (_user == null)
        {
            //Here you could create the super admin who will maintain the web app
            var poweruser = new ApplicationUser
            {
                UserName = "Admin",
                Email = "admin@gmail.com",
            };
            string adminPassword = "Abc*123";

            var createPowerUser = await UserManager.CreateAsync(poweruser, adminPassword);
            if (createPowerUser.Succeeded)
            {
                //here we tie the new user to the role
                await UserManager.AddToRoleAsync(poweruser, "Admin");

            }
        }
    }
专用异步任务CreateRoles(IServiceProvider服务提供者)
{
//初始化自定义角色
var rolemager=serviceProvider.GetRequiredService();
var UserManager=serviceProvider.GetRequiredService();
字符串[]roleNames={“Admin”,“Operacional”};
识别结果角色结果;
foreach(roleName中的变量roleName)
{
var roleExist=wait rolemager.RoleExistsAsync(roleName);
//确保该角色不存在
如果(!roleExist)
{
//创建角色并将其种子植入数据库:
roleResult=await RoleManager.CreateAsync(新的IdentityRole(roleName));
}
}
//使用管理员电子邮件查找用户
var\u user=await UserManager.findbyemailsync(“admin@gmail.com");
//检查用户是否存在
如果(_user==null)
{
//在这里,你可以创建超级管理员谁将维护web应用程序
var poweruser=新应用程序用户
{
UserName=“Admin”,
电子邮件=”admin@gmail.com",
};
字符串adminPassword=“Abc*123”;
var createPowerUser=await UserManager.CreateAsync(poweruser,adminPassword);
如果(createPowerUser.successed)
{
//这里,我们将新用户绑定到角色
wait UserManager.AddToRoleAsync(poweruser,“Admin”);
}
}
}

public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境、IServiceProvider服务提供商)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
//信号机
//字符串caminho=configuration[“应用设置:服务商”]+“/myHub”;
字符串caminho=Configuration[“应用设置:服务商”]+“/myHub”;
//MapHub(卡米尼奥);
//app.usesigner(路由=>
//{
//路线:MapHub(卡米尼奥);
//});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapHub(“/myHub”);
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{id?}”);
endpoints.MapRazorPages();
});
CreateRoles(serviceProvider).Wait();
}
当我运行该项目时,它在CreateRoles(serviceProvider)中给出错误“System.AggregateException:'没有类型为'Microsoft.AspNetCore.Identity.UserManager`1[ProjectName.ApplicationUser]'的服务已注册。当容器被销毁时可启用)”。Wait();
为什么会发生这种情况?

尝试添加
服务。AddDefaultIdentity。

这是否回答了您的问题?请共享startup.cs ConfigureServices方法,好吗?您似乎使用了错误的applicationuser或identityuser型号。
           public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

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

        app.UseAuthentication();

        //SIGNAL R

        //String caminho = configuration["AppSettings:Servidor"] + "/myHub";
        String caminho = Configuration["AppSettings:Servidor"] + "/myHub";

        //endpoints.MapHub<MyHub>(caminho);
        //app.UseSignalR(route =>
        //{
        //    route.MapHub<MyHub>(caminho);

        //});

        app.UseRouting();
       app.UseAuthorization();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<MyHub>("/myHub");
            endpoints.MapControllerRoute(
                name: "default",
               pattern: "{controller=Home}/{action=Index}/{id?}");
            endpoints.MapRazorPages();
        });

        CreateRoles(serviceProvider).Wait();

    }