asp.net CreateRoles()从.NET 3.1迁移到.NET 6

hof1towb  于 2023-02-10  发布在  .NET
关注(0)|答案(1)|浏览(145)

目前.NET 6不使用startup.cs,只使用program.cs。我正试图将所有内容都移到只使用program.cs,但在CreateRoles()部分有一些问题。
在我的.NET 3.1中,我更改了

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDBContext>();

我的Configure函数中有CreateRoles(serviceProvider).Wait();,并且

public async Task CreateRoles(IServiceProvider serviceProvider)
        {
            var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();

            string[] roleNames = { "UserManager", "Manager", "Worker", "User" };

            IdentityResult identityResult;

            foreach(var roleName in roleNames)
            {
                var roleExist = await RoleManager.RoleExistsAsync(roleName);
                if (!roleExist)
                {
                    identityResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
                }
            }

            var usermanager = await UserManager.FindByEmailAsync("UserManager@UserManager.com");
            if (usermanager == null)
            {
                var userManager = new IdentityUser { UserName = "UserManager@UserManager.com", Email = "UserManager@UserManager.com", EmailConfirmed = true };
                var createUserManager = await UserManager.CreateAsync(userManager,"UserManager2022!");
                if (createUserManager.Succeeded)
                {
                    await UserManager.AddToRoleAsync(userManager, "UserManager");
                }
            }
        }

我删除了函数名,并将其内容直接添加到program.cs中,删除了CreateRoles(serviceProvider).Wait();,但现在我的项目甚至无法运行。该项目能够成功构建,但运行时无法连接到Web服务器。如果我回去拥有startup.csprogram.cs,该项目运行没有任何问题。
这是我目前在program.cs上拥有的。

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<ApplicationDBContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default Connection")));
builder.Services.AddDbContext<ManagementContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default Connection")));
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false).AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDBContext>();
builder.Services.AddTransient<IProductInterface,ProductRepo>();

var app = builder.Build();

using (var serviceScope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
    var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDBContext>();
    //context.Database.EnsureDeleted(); //Add to clear db at startup.
    context.Database.Migrate();
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/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.UseRouting();
app.UseAuthentication();;

app.UseAuthorization();

var UserManager = app.Services.GetRequiredService<UserManager<IdentityUser>>();
var RoleManager = app.Services.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "UserManager", "Manager", "Worker", "User" };

IdentityResult identityResult;

foreach (var roleName in roleNames)
{
    var roleExist = await RoleManager.RoleExistsAsync(roleName);
    if (!roleExist)
    {
        identityResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
    }
}

var usermanager = await UserManager.FindByEmailAsync("UserManager@UserManager.com");
if (usermanager == null)
{
    var userManager = new IdentityUser { UserName = "UserManager@UserManager.com", Email = "UserManager@UserManager.com", EmailConfirmed = true };
    var createUserManager = await UserManager.CreateAsync(userManager, "UserManager2022!");
    if (createUserManager.Succeeded)
    {
        await UserManager.AddToRoleAsync(userManager, "UserManager");
    }
}

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

app.Run();

我知道一个解决方案是创建一个startup.csprogram.cs,但我只想使用program.cs

hgc7kmma

hgc7kmma1#

你想要下面这样的吗?
调用builder.build()后,app.services将解析为IServiceProvider。

var app = builder.Build();
CreateRolesAsync(app.Services);
...
app.Run();
async Task CreateRolesAsync( IServiceProvider serviceProvider)
{..}

相关问题