CreateRoles() moving from .NET 3.1 to .NET 6

huangapple go评论64阅读模式
英文:

CreateRoles() moving from .NET 3.1 to .NET 6

问题

.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)
{
    // ...
}

你删除了函数名称,将其内容直接添加到 program.cs 中,并删除了 CreateRoles(serviceProvider).Wait();,但现在你的项目甚至无法运行。尽管项目能够成功构建,但在运行时无法连接到 Web 服务器。如果回到同时使用 startup.csprogram.cs,项目可以正常运行。

以下是你当前在 program.cs 中的代码:

var builder = WebApplication.CreateBuilder(args);

// 添加服务到容器
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.Migrate();
}

// 配置 HTTP 请求管道
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    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

英文:

Currently .NET 6 does not use startup.cs and only uses program.cs. I am trying to move everything over to use only program.cs but have some issues at the CreateRoles() portion.

In my .NET 3.1 I changed

services.AddDefaultIdentity&lt;IdentityUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = false)
    .AddRoles&lt;IdentityRole&gt;()
    .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();

to

builder.Services.AddDefaultIdentity&lt;IdentityUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = false)
    .AddRoles&lt;IdentityRole&gt;()
    .AddEntityFrameworkStores&lt;ApplicationDBContext&gt;();

I have CreateRoles(serviceProvider).Wait(); in my Configure function and

public async Task CreateRoles(IServiceProvider serviceProvider)
        {
            var UserManager = serviceProvider.GetRequiredService&lt;UserManager&lt;IdentityUser&gt;&gt;();
            var RoleManager = serviceProvider.GetRequiredService&lt;RoleManager&lt;IdentityRole&gt;&gt;();

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

            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(&quot;UserManager@UserManager.com&quot;);
            if (usermanager == null)
            {
                var userManager = new IdentityUser { UserName = &quot;UserManager@UserManager.com&quot;, Email = &quot;UserManager@UserManager.com&quot;, EmailConfirmed = true };
                var createUserManager = await UserManager.CreateAsync(userManager,&quot;UserManager2022!&quot;);
                if (createUserManager.Succeeded)
                {
                    await UserManager.AddToRoleAsync(userManager, &quot;UserManager&quot;);
                }
            }
        }

I removed the function name and added its contents directly to program.cs and removed
CreateRoles(serviceProvider).Wait(); but now my project won't even run. The project is able to build successfully but when running it wont connect to web server. If I was to go back to having both startup.cs and program.cs the project runs with no issues.

This is currently what I have on program.cs.

var builder = WebApplication.CreateBuilder(args);

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

var app = builder.Build();

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

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler(&quot;/Home/Error&quot;);
    // 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&lt;UserManager&lt;IdentityUser&gt;&gt;();
var RoleManager = app.Services.GetRequiredService&lt;RoleManager&lt;IdentityRole&gt;&gt;();
string[] roleNames = { &quot;UserManager&quot;, &quot;Manager&quot;, &quot;Worker&quot;, &quot;User&quot; };

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(&quot;UserManager@UserManager.com&quot;);
if (usermanager == null)
{
    var userManager = new IdentityUser { UserName = &quot;UserManager@UserManager.com&quot;, Email = &quot;UserManager@UserManager.com&quot;, EmailConfirmed = true };
    var createUserManager = await UserManager.CreateAsync(userManager, &quot;UserManager2022!&quot;);
    if (createUserManager.Succeeded)
    {
        await UserManager.AddToRoleAsync(userManager, &quot;UserManager&quot;);
    }
}

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

app.Run();

I know a solution would just be to create a startup.cs and program.cs but I want to use just program.cs.

答案1

得分: 0

After you call builder.Build() the app.Services resolves as an IServiceProvider.

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

英文:

Do you want something like below ?

After you call builder.Build() the app.Services resolves as an IServiceProvider.

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

huangapple
  • 本文由 发表于 2023年2月9日 03:03:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定