此问题可能是因为未正确配置服务集合。确保在Startup.cs文件中正确地注入了Identity服务并配置了Identity选项。
以下是正确注册Identity服务和配置Identity选项的示例代码:
public void ConfigureServices(IServiceCollection services)
{
// 注册 Identity 服务
services.AddDefaultIdentity(options =>
{
// 配置 Password 验证规则
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 8;
})
.AddRoles()
.AddEntityFrameworkStores();
// 添加认证服务
services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();
// 添加授权服务
services.AddAuthorization(options =>
{
options.AddPolicy("RequireAdministratorRole", policy => policy.RequireRole("Administrator"));
});
}
确保在使用UserManager和RoleManager时注入了正确的服务(例如,ApplicationUser和IdentityRole)。
以下是在Blazor页面中使用UserManager和RoleManager的示例代码:
@inject UserManager UserManager
@inject RoleManager RoleManager
@code {
private async Task CreateUser()
{
var user = new ApplicationUser { UserName = "testuser@example.com", Email = "testuser@example.com" };
var result = await UserManager.CreateAsync(user, "MyP@ssw0rd!");
if (result.Succeeded)
{
await UserManager.AddToRoleAsync(user, "User");
}
}
private async Task CreateRole()
{
var role = new IdentityRole { Name = "Administrator" };
var result = await RoleManager.CreateAsync(role);
}
}