英文:
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.cs
和 program.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.cs
和 program.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<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
to
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDBContext>();
I have CreateRoles(serviceProvider).Wait();
in my Configure
function and
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");
}
}
}
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<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();
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)
{..}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论