简体   繁体   English

如何访问用户管理器<identityuser>来自 asp.net 核心 7.0 中 program.cs 中的 WebApplication 实例应用程序的实例</identityuser>

[英]How to access UserManager<IdentityUser> instance from WebApplication instance app in program.cs in asp.net core 7.0

I need to access UserManager instance to seed IdentityUser data, I am doing in program.cs file Below is given code snippet我需要访问 UserManager 实例来播种 IdentityUser 数据,我在 program.cs 文件中做下面给出了代码片段

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services
    .AddDefaultIdentity<MyIdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppDbContext>();

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
});

builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();


builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller = Home}/{action = Index}/{Id?}"
    );
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapDefaultControllerRoute();
app.MapRazorPages();

var scopeFactory = app.Services.GetRequiredService<IServiceScopeFactory>();
var scope = scopeFactory.CreateScope();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<MyIdentityUser>>();

SeedInitialData.SeedData(roleManager, userManager);

app.Run();

and I receive this exception我收到这个例外

InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered. InvalidOperationException:没有注册类型为“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”的服务。 Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider 提供者,类型 serviceType)

Please help me, how to find this issue.请帮助我,如何找到这个问题。 regards问候

I read many articles, and I tried some of them, none of them worked for me.我读了很多文章,我尝试了其中一些,但没有一篇对我有用。

I create a simple demo to show how to seed data to identity in asp.net core, You can refer to it.我创建了一个简单的演示来展示如何在 asp.net 核心中将数据播种到身份,您可以参考它。

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        //.........

        builder.Services.AddIdentity<IdentityUser,IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores<ApplicationDbContext>();
        

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        //........
        app.UseAuthorization();

        using (var scope = app.Services.CreateScope())
        {
            //Resolve ASP .NET Core Identity with DI help
            var userManager = (UserManager<IdentityUser>)scope.ServiceProvider.GetService(typeof(UserManager<IdentityUser>));
            var roleManager = (RoleManager<IdentityRole>)scope.ServiceProvider.GetService(typeof(RoleManager<IdentityRole>));
            // do you things here

            MyIdentityDataInitializer.SeedData(userManager, roleManager);
        }

       //........

        app.Run();
    }
}

MyIdentityDataInitializer class我的身份数据初始化器 class

public static  class MyIdentityDataInitializer
    {
        public static void SeedData(UserManager<IdentityUser> userManager,RoleManager<IdentityRole> roleManager)
        {
            SeedRoles(roleManager);
            SeedUsers(userManager);
        }

        public static void SeedUsers(UserManager<IdentityUser> userManager)
        {
            if (userManager.FindByNameAsync("user1").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user1";
                user.Email = "user1@localhost";               
                IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "NormalUser").Wait();
                }
            }


            if (userManager.FindByNameAsync("user2").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user2";
                user.Email = "user2@localhost";
                IdentityResult result = userManager.CreateAsync(user, "Password123!!!").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "Administrator").Wait();
                }
            }
        }

        public static void SeedRoles(RoleManager<IdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("NormalUser").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "NormalUser";
                
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }


            if (!roleManager.RoleExistsAsync("Administrator").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "Administrator";
               
                IdentityResult roleResult = roleManager.CreateAsync(role).Result;
            }
        }
    }

Now when I run my project, The data will be seeded successfully.现在当我运行我的项目时,数据将被成功播种。

在此处输入图像描述

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 ASP.NET Core 中的 Program.cs 访问 IWebHostEnvironment - How to access IWebHostEnvironment from Program.cs in ASP.NET Core ASP.NET Core 6 MVC:如何从 controller 访问 Program.cs 中定义的变量值? - ASP.NET Core 6 MVC : how to access a variable's value that is defined in Program.cs from a controller? 如何返回在 Program.cs ASP.Net core 6 中找不到 - How to return not found in Program.cs ASP.Net core 6 如何从 program.cs 中的 appsettings 中读取 UrlPrefixes - asp.net core 3.1 - how to read UrlPrefixes from appsettings in program.cs - asp.net core 3.1 ASP.NET 核心 Web API - 如何将 .NET 核心 5 中的 SetupSerilog 转换为 .NET 核心 6 Program.cs - ASP.NET Core Web API - How to convert SetupSerilog in .NET Core 5 to .NET Core 6 Program.cs ASP.NET 核心程序.cs配置 - ASP.NET Core program.cs configuration 在 ASP.NET Core 6 Program.cs 中配置 EF - Configuring EF in ASP.NET Core 6 Program.cs 避免在ASP.NET Core Program.cs中使用静态值 - Avoid static value in ASP.NET Core Program.cs 如何在 .NET 6 Program.cs 类中获取 ILoggerFactory 实例 - How to get ILoggerFactory instance in .NET 6 Program.cs class .NET Core 6 - 如何在启动期间在 Program.cs 中获取没有依赖注入的 ILogger 实例 - .NET Core 6 - How to get an ILogger instance without Dependency Injection in Program.cs during Startup
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM