gpt4 book ai didi

c# - 无法获取 UserManager 类

转载 作者:行者123 更新时间:2023-11-30 14:48:53 25 4
gpt4 key购买 nike

我想做的是添加一个新的管理员用户并为其分配管理员角色。所以..我转到 Configure 方法中的 Startup.cs 类并编写了以下代码:

var context = app.ApplicationServices.GetService<ApplicationDbContext>();

// Getting required parameters in order to get the user manager
var userStore = new UserStore<ApplicationUser>(context);

// Finally! get the user manager!
var userManager = new UserManager<ApplicationUser>(userStore);

但是,我收到以下错误消息:

Severity Code Description Project File Line Suppression State Error CS7036 There is no argument given that corresponds to the required formal parameter 'optionsAccessor' of UserManager.UserManager(IUserStore, IOptions, IPasswordHasher, IEnumerable>, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, IServiceProvider, ILogger>)' FinalProject..NETCoreApp,Version=v1.0 C:\Users\Or Natan\Documents\Visual Studio 2015\Projects\FinalProject\src\FinalProject\Startup.cs 101 Active

这个错误让我很难受。显然我需要 userManager 来创建新用户,但我无法初始化这个东西。

最佳答案

您可以使用 dependency injection获取 UserManager 的实例。只需在配置方法中添加一个参数,如下所示:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)

然后您可以创建用户和角色。我通常将这段代码移到一个静态类中......

public static class DbInitializer
{
public static async Task Initialize(ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
// Ensure that the database exists and all pending migrations are applied.
context.Database.Migrate();

// Create roles
string[] roles = new string[] { "UserManager", "StaffManager" };
foreach (string role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
}

// Create admin user
if (!context.Users.Any())
{
await userManager.CreateAsync(new ApplicationUser() { UserName = "info@example.com", Email = "info@example.com" }, "p@ssw0rd");
}

// Ensure admin privileges
ApplicationUser admin = await userManager.FindByEmailAsync("info@example.com");
foreach (string role in roles)
{
await userManager.AddToRoleAsync(admin, role);
}
}
}

...并调用Startup.Configure方法中的方法:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ApplicationDbContext context, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
// Code omitted for brevity

// Create seed data
DbInitializer.Initialize(context, userManager, roleManager).Wait();
}

在 Entity Framework Core 的下一个版本中 database seeding will be added as a feature .

关于c# - 无法获取 UserManager 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40027388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com