我在asp.net核心项目中编写了向用户添加角色的代码
这是我的角色控制器。
public class RolesController : Controller
{
RoleManager<IdentityRole> _roleManager;
UserManager<AspNetUsers> _userManager;
public RolesController(RoleManager<IdentityRole> roleManager, UserManager<AspNetUsers> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
public IActionResult Index() => View(_roleManager.Roles.ToList());
public IActionResult Create() => View();
[HttpPost]
public async Task<IActionResult> Create(string name)
{
if (!string.IsNullOrEmpty(name))
{
IdentityResult result = await _roleManager.CreateAsync(new IdentityRole(name));
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
return View(name);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
IdentityRole role = await _roleManager.FindByIdAsync(id);
if (role != null)
{
IdentityResult result = await _roleManager.DeleteAsync(role);
}
return RedirectToAction("Index");
}
public IActionResult UserList() => View(_userManager.Users.ToList());
public async Task<IActionResult> Edit(string userId)
{
// получаем пользователя
AspNetUsers user = await _userManager.FindByIdAsync(userId);
if(user!=null)
{
// получем список ролей пользователя
var userRoles = await _userManager.GetRolesAsync(user);
var allRoles = _roleManager.Roles.ToList();
ChangeRoleViewModel model = new ChangeRoleViewModel
{
UserId = user.Id,
UserEmail = user.Email,
UserRoles = userRoles,
AllRoles = allRoles
};
return View(model);
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Edit(string userId, List<string> roles)
{
AspNetUsers user = await _userManager.FindByIdAsync(userId);
if(user!=null)
{
var userRoles = await _userManager.GetRolesAsync(user);
var allRoles = _roleManager.Roles.ToList();
var addedRoles = roles.Except(userRoles);
var removedRoles = userRoles.Except(roles);
await _userManager.AddToRolesAsync(user, addedRoles);
await _userManager.RemoveFromRolesAsync(user, removedRoles);
return RedirectToAction("UserList");
}
return NotFound();
}
}
但是当我运行应用程序并转到“角色”控制器时。我收到此错误
处理请求时发生未处理的异常。 InvalidOperationException:尝试激活“ VchasnoCrm.Controllers.RolesController”时,无法解析类型为“ Microsoft.AspNetCore.Identity.RoleManager`1 [Microsoft.AspNetCore.Identity.IdentityRole]”的服务。 Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,Type type,Type requiredBy,bool isDefaultParameterRequired)
我该如何解决?
答案 0 :(得分:2)
在startup.cs
文件中,您必须在其中一项服务中添加.addRoles<IdentityRole>()
:
services.AddDefaultIdentity<Usuarios>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //Line that can help you
.AddEntityFrameworkStores<ApplicationDbContext>();
答案 1 :(得分:1)
因此,为了使它起作用,我需要将此行添加到Startup.cs文件中
services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();
然后像这样更改我的角色控制器
public class RolesController : Controller
{
RoleManager<IdentityRole> _roleManager;
UserManager<IdentityUser> _userManager;
public RolesController(RoleManager<IdentityRole> roleManager, UserManager<IdentityUser> userManager)
{
_roleManager = roleManager;
_userManager = userManager;
}
public IActionResult Index() => View(_roleManager.Roles.ToList());
public IActionResult Create() => View();
[HttpPost]
public async Task<IActionResult> Create(string name)
{
if (!string.IsNullOrEmpty(name))
{
IdentityResult result = await _roleManager.CreateAsync(new IdentityRole(name));
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
}
return View(name);
}
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
IdentityRole role = await _roleManager.FindByIdAsync(id);
if (role != null)
{
IdentityResult result = await _roleManager.DeleteAsync(role);
}
return RedirectToAction("Index");
}
public IActionResult UserList() => View(_userManager.Users.ToList());
public async Task<IActionResult> Edit(string userId)
{
// получаем пользователя
IdentityUser user = await _userManager.FindByIdAsync(userId);
if(user!=null)
{
// получем список ролей пользователя
var userRoles = await _userManager.GetRolesAsync(user);
var allRoles = _roleManager.Roles.ToList();
ChangeRoleViewModel model = new ChangeRoleViewModel
{
UserId = user.Id,
UserEmail = user.Email,
UserRoles = userRoles,
AllRoles = allRoles
};
return View(model);
}
return NotFound();
}
[HttpPost]
public async Task<IActionResult> Edit(string userId, List<string> roles)
{
// получаем пользователя
IdentityUser user = await _userManager.FindByIdAsync(userId);
if(user!=null)
{
// получем список ролей пользователя
var userRoles = await _userManager.GetRolesAsync(user);
// получаем все роли
var allRoles = _roleManager.Roles.ToList();
// получаем список ролей, которые были добавлены
var addedRoles = roles.Except(userRoles);
// получаем роли, которые были удалены
var removedRoles = userRoles.Except(roles);
await _userManager.AddToRolesAsync(user, addedRoles);
await _userManager.RemoveFromRolesAsync(user, removedRoles);
return RedirectToAction("UserList");
}
return NotFound();
}
}
答案 2 :(得分:1)
在Net Core 3.1中,有两个不同的ASP.NET Core Identity重载,第一个版本名为DefaultIdentity,您没有机会同时设置用户和角色,因此语法看起来像
services.AddDefaultIdentity<IdentityUser>(options => ...
身份的第二版使用用户和角色,外观为
services.AddIdentity<IdentityUser, IdentityRole>(options => ...
它是身份的不同版本,首先包含IdentityUI,其次不包含IdentityUI。 但是,如果您将Roles服务添加为
,则可以在第一个版本中包含角色。services.AddDefaultIdentity<IdentityUser>(options =>...).AddRoles<IdentityRole>()...
如果您已将Roles服务包含在服务集中,则可以将Roles to Configure方法插入为
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbContextOptions<ApplicationDbContext> identityDbContextOptions, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
如果您注射,通常会出现此错误消息
RoleManager<IdentityRole> roleManager
在项目的任何位置,而无需添加IdentityRole服务(通过第一种或第二种方式)。
答案 3 :(得分:1)
在 Net Core 3.1 中,您需要为身份服务配置辅助函数。为此,您需要创建 Microsoft.AspNetCore.Identity.IdentityBuilder 的新实例。要激活 RoleManager 服务 -
var builder = services.AddIdentityCore<AppUser>();
builder.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>();
答案 4 :(得分:0)
使用.net core 3.0,Identity Server 4和angular SPA默认模板(由Rider自动生成的项目)时,我遇到了类似的问题。
在我的情况下,Startup.cs
包含:
services.AddDefaultIdentity<ApplicationUser().AddEntityFrameworkStores<ApplicationDbContext>();
我必须添加.AddRoles<IdentityRole>()
并将其更改为:
services.AddDefaultIdentity<ApplicationUser().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();