我在Startup.cs
类中访问RoleManager
和UserManager
时遇到问题。这是我用来注册Identity
的代码:
services.AddIdentity<User, IdentityRole>(cfg =>
{
cfg.User.RequireUniqueEmail = true;
cfg.SignIn.RequireConfirmedEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<CarinioContext>()
.AddDefaultTokenProviders()
.AddErrorDescriber<CustomIdentityErrorDescriber>();
User 是我的自定义类,它继承自IdentityUser
并通过一些其他属性对其进行扩展。
我在 startup.cs
类中有一个函数来创建角色和用户。我知道这对播种不是很好,我将来会改变它,但我需要先让它以这种方式工作。这是我的代码:
private async Task CreateRoles()
{
//adding custom roles
var UserManager = _serviceProvicer.GetRequiredService<UserManager<IdentityUser>>();
var RoleManager = _serviceProvicer.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "Admin", "Client", "Driver" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
//creating the roles and seeding them to the database
var roleExist = await RoleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
//creating a super user who could maintain the web app
var poweruser = new User
{
UserName = _configuration.GetSection("UserSettings")["UserName"],
Email = _configuration.GetSection("UserSettings")["UserEmail"],
PhoneNumber = _configuration.GetSection("UserSettings")["PhoneNumer"],
};
string UserPassword = _configuration.GetSection("UserSettings")["UserPassword"];
var _user = await UserManager.FindByEmailAsync(_configuration.GetSection("UserSettings")["UserEmail"]);
if (_user == null)
{
var createPowerUser = await UserManager.CreateAsync(poweruser, UserPassword);
if (createPowerUser.Succeeded)
{
//here we tie the new user to the "Admin" role
await UserManager.AddToRoleAsync(poweruser, "Admin");
}
}
}
程序总是崩溃说:
"One or more errors occurred. (No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.)"
UserManager
也是如此:
"One or more errors occurred. (No service for type 'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]' has been registered.)"
我的猜测是我没有以正确的方式访问UserManager
和RoleManager
。有谁知道解决方案?
dotnet core具有出色的功能,可以在第一次播种角色或用户在 efcore 的实体配置部分中,您可以使用 blow 类来创建默认角色:
public class RoleConfiguration : IEntityTypeConfiguration<Role>
{
public void Configure(EntityTypeBuilder<Role> builder)
{
builder.HasData(new Role() {Id=1, Name = "Manager", NormalizedName = "MANAGER",Title="manager" }, new Role() {Id=2, Name = "Student", NormalizedName = "STUDENT",Title="student" });
}
}
尝试修改您的代码:
var UserManager = _serviceProvicer.GetRequiredService<UserManager<IdentityUser>>();
自:
var UserManager = _serviceProvicer.GetRequiredService<UserManager<User>>();
如果创建继承自 IdentityUser
的自定义类,则需要在 ConfigureServices
中注册新User
:
services.AddIdentity<User, IdentityRole>
在CarinioContext
中,例如:
public class CarinioContext: IdentityDbContext<User, IdentityRole, string>
在_LoginPartial.cshtml
:
@inject SignInManager<User> SignInManager
@inject UserManager<User> UserManager