![](/img/trans.png)
[英]After change ApplicationUser.cs I get error Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`
[英]Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`
我在我的 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)
我该如何解决这个问题?
在 Net Core 3.1 中有两个不同的 ASP.NET Core Identity 重载,第一个版本名为 DefaultIdentity,您没有机会同时设置 User 和 Roles,因此语法如下
services.AddDefaultIdentity<IdentityUser>(options => ...
Identity 的第二个版本使用 User 和 Roles 并且看起来像
services.AddIdentity<IdentityUser, IdentityRole>(options => ...
这是身份的不同版本,第一个包含 IdentityUI,第二个不包含 IdentityUI。 但是,如果您将角色服务添加为
services.AddDefaultIdentity<IdentityUser>(options =>...).AddRoles<IdentityRole>()...
如果您已将 Roles 服务包含到您的服务集中,则可以将 Roles 注入到 Configure 方法中,如下所示
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbContextOptions<ApplicationDbContext> identityDbContextOptions, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
如果您注入,通常会出现此错误消息
RoleManager<IdentityRole> roleManager
在项目的任何地方而不添加 IdentityRole 服务(通过第一种或第二种方式)。
我在使用 .net core 3.0、身份服务器 4 和角度 SPA 默认模板(由 Rider 自动生成的项目)时遇到了类似的问题。
在我的案例中, Startup.cs
包含:
services.AddDefaultIdentity<ApplicationUser().AddEntityFrameworkStores<ApplicationDbContext>();
我必须添加.AddRoles<IdentityRole>()
并将其更改为:
services.AddDefaultIdentity<ApplicationUser().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
在startup.cs
文件中,您必须在其中一项服务中添加.addRoles<IdentityRole>()
:
services.AddDefaultIdentity<Usuarios>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //Line that can help you
.AddEntityFrameworkStores<ApplicationDbContext>();
所以为了让它工作,我需要将这一行添加到 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();
}
}
在 Net Core 3.1 中,您需要为身份服务配置辅助函数。 为此,您需要创建一个新的 Microsoft.AspNetCore.Identity.IdentityBuilder 实例。要激活 RoleManager 服务 -
var builder = services.AddIdentityCore<AppUser>(); builder.AddRoles<IdentityRole>().AddEntityFrameworkStores<AppIdentityDbContext>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.