C# 无法解析类型为';Microsoft.AspNetCore.Identity.RoleManager`
我正在编写代码,以便在asp.net核心项目中向用户添加角色 这是我的角色控制器C# 无法解析类型为';Microsoft.AspNetCore.Identity.RoleManager`,c#,asp.net,.net,asp.net-identity,C#,Asp.net,.net,Asp.net Identity,我正在编写代码,以便在asp.net核心项目中向用户添加角色 这是我的角色控制器 public class RolesController : Controller { RoleManager<IdentityRole> _roleManager; UserManager<AspNetUsers> _userManager; public RolesController(RoleManager<IdentityRole> roleMan
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();
}
}
公共类角色控制器:控制器
{
角色经理(rolemanger);
用户管理器(UserManager);;
公共角色控制器(角色管理器角色管理器,用户管理器用户管理器)
{
_roleManager=roleManager;
_userManager=userManager;
}
public IActionResult Index()=>视图(_rolemager.Roles.ToList());
public IActionResult Create()=>View();
[HttpPost]
公共异步任务创建(字符串名称)
{
如果(!string.IsNullOrEmpty(名称))
{
IdentityResult result=await _roleManager.CreateAsync(新IdentityRole(名称));
if(result.successed)
{
返回操作(“索引”);
}
其他的
{
foreach(result.Errors中的变量错误)
{
AddModelError(string.Empty,error.Description);
}
}
}
返回视图(名称);
}
[HttpPost]
公共异步任务删除(字符串id)
{
IdentityRole=wait_rolemanger.FindByIdAsync(id);
if(角色!=null)
{
IdentityResult结果=等待_roleManager.DeleteAsync(角色);
}
返回操作(“索引”);
}
public IActionResult UserList()=>视图(_userManager.Users.ToList());
公共异步任务编辑(字符串用户ID)
{
// получаем пользователя
AspNetUsers user=await\u userManager.FindByIdAsync(userId);
如果(用户!=null)
{
// получем список ролей пользователя
var userRoles=await\u userManager.GetRolesAsync(用户);
var allRoles=_roleManager.Roles.ToList();
ChangeRoleView模型=新的ChangeRoleView模型
{
UserId=user.Id,
UserEmail=user.Email,
UserRoles=UserRoles,
所有角色=所有角色
};
返回视图(模型);
}
返回NotFound();
}
[HttpPost]
公共异步任务编辑(字符串用户ID、列表角色)
{
AspNetUsers user=await\u userManager.FindByIdAsync(userId);
如果(用户!=null)
{
var userRoles=await\u userManager.GetRolesAsync(用户);
var allRoles=_roleManager.Roles.ToList();
var addedRoles=角色。除了(userRoles);
var removedRoles=userRoles.Except(角色);
wait_userManager.AddToRolesAsync(用户,adddroles);
wait_userManager.RemoveFromRolesAsync(用户,removedRoles);
返回重定向到操作(“用户列表”);
}
返回NotFound();
}
}
但当我运行应用程序并转到角色控制器时。我得到这个错误
处理请求时发生未处理的异常。
InvalidOperationException:在尝试激活“VchasnoCrm.Controllers.RoleController”时,无法解析类型为“Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.Identity.IdentityRole]”的服务。
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型requiredBy,bool isDefaultParameterRequired)
如何修复此问题?因此,要使其正常工作,我需要将此行添加到Startup.cs文件中
services.AddIdentity<IdentityUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity().AddEntityFrameworkStores();
像这样改变我的角色
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();
}
}
公共类角色控制器:控制器
{
角色经理(rolemanger);
用户管理器(UserManager);;
公共角色控制器(角色管理器角色管理器,用户管理器用户管理器)
{
_roleManager=roleManager;
_userManager=userManager;
}
public IActionResult Index()=>视图(_rolemager.Roles.ToList());
public IActionResult Create()=>View();
[HttpPost]
公共异步任务创建(字符串名称)
{
如果(!string.IsNullOrEmpty(名称))
{
IdentityResult result=await _roleManager.CreateAsync(新IdentityRole(名称));
if(result.successed)
{
返回操作(“索引”);
}
其他的
{
foreach(result.Errors中的变量错误)
{
AddModelError(string.Empty,error.Description);
}
}
}
返回视图(名称);
}
[HttpPost]
公共异步任务删除(字符串id)
{
IdentityRole=wait_rolemanger.FindByIdAsync(id);
if(角色!=null)
{
IdentityResult结果=等待_roleManager.DeleteAsync(角色);
}
返回操作(“索引”);
}
public IActionResult UserList()=>视图(_userManager.Users.ToList());
公共异步任务编辑(字符串用户ID)
{
// получаем пользователя
IdentityUser user=wait_userManager.FindByIdAsync(userId);
如果(用户!=null)
{
// получем список ролей пользователя
var userRoles=await\u userManager.GetRolesAsync(用户);
var allRoles=_roleManager.Roles.ToList();
ChangeRoleView模型=新的ChangeRoleView模型
{
UserId=user.Id,
UserEmail=user.Email,
UserRoles=UserRoles,
所有角色=所有角色
};
返回视图(模型);
}
返回NotFound();
}
[HttpPost]
公共异步任务编辑(字符串用户ID、列表角色)
{
// получаем пользователя
IdentityUser user=wait_userManager.FindByIdAsync(userId);
如果(用户!=null)
{
// получем список ролей пользовател?
services.AddDefaultIdentity<ApplicationUser().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddDefaultIdentity<ApplicationUser().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
services.AddDefaultIdentity<IdentityUser>(options => ...
services.AddIdentity<IdentityUser, IdentityRole>(options => ...
services.AddDefaultIdentity<IdentityUser>(options =>...).AddRoles<IdentityRole>()...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbContextOptions<ApplicationDbContext> identityDbContextOptions, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
RoleManager<IdentityRole> roleManager
services.AddDefaultIdentity<Usuarios>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //Line that can help you
.AddEntityFrameworkStores<ApplicationDbContext>();
var builder = services.AddIdentityCore<AppUser>();
builder.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>();