无法解析类型“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();
}
}
但是当我 运行 应用程序并转到角色控制器时。我得到这个错误
An unhandled exception occurred while processing the request.
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'VchasnoCrm.Controllers.RolesController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
我该如何解决这个问题?
因此,为了使其有效,我需要将此行添加到 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.0、身份服务器 4 和 angular SPA 默认模板(由 Rider 自动生成的项目)时遇到了类似的问题。
在我的案例中 Startup.cs
包含:
services.AddDefaultIdentity<ApplicationUser().AddEntityFrameworkStores<ApplicationDbContext>();
我必须添加 .AddRoles<IdentityRole>()
并将其更改为:
services.AddDefaultIdentity<ApplicationUser().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
在 Net Core 3.1 中有两个不同的 ASP.NET Core Identity 重载,第一个版本名为 DefaultIdentity,您没有机会同时设置 User 和 Roles,因此语法看起来像
services.AddDefaultIdentity<IdentityUser>(options => ...
身份的第二个版本使用用户和角色,看起来像
services.AddIdentity<IdentityUser, IdentityRole>(options => ...
这是不同版本的身份,第一个包含 IdentityUI,第二个不包含 IdentityUI。
但是,如果您将角色服务添加为
,您可以将角色包含到第一个版本中
services.AddDefaultIdentity<IdentityUser>(options =>...).AddRoles<IdentityRole>()...
如果您已将角色服务包含到您的服务集中,您可以将角色注入到 Configure 方法中,如
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbContextOptions<ApplicationDbContext> identityDbContextOptions, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
如果您注入
,通常会出现此错误消息
RoleManager<IdentityRole> roleManager
在项目的任何地方,无需添加 IdentityRole 服务(通过第一种或第二种方式)。
在startup.cs
文件中,您必须在其中一项服务中添加.addRoles<IdentityRole>()
:
services.AddDefaultIdentity<Usuarios>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //Line that can help you
.AddEntityFrameworkStores<ApplicationDbContext>();
在Net Core 3.1中,您需要为身份服务配置辅助函数。为此,您需要创建一个新实例 Microsoft.AspNetCore.Identity.IdentityBuilder.To activate RoleManager service -
- 转到您的 startup.cs 文件。
- 在我的例子中,语法看起来像 -
var builder = services.AddIdentityCore<AppUser>();
builder.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>();
我在 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();
}
}
但是当我 运行 应用程序并转到角色控制器时。我得到这个错误
An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' while attempting to activate 'VchasnoCrm.Controllers.RolesController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
我该如何解决这个问题?
因此,为了使其有效,我需要将此行添加到 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.0、身份服务器 4 和 angular SPA 默认模板(由 Rider 自动生成的项目)时遇到了类似的问题。
在我的案例中 Startup.cs
包含:
services.AddDefaultIdentity<ApplicationUser().AddEntityFrameworkStores<ApplicationDbContext>();
我必须添加 .AddRoles<IdentityRole>()
并将其更改为:
services.AddDefaultIdentity<ApplicationUser().AddRoles<IdentityRole>().AddEntityFrameworkStores<ApplicationDbContext>();
在 Net Core 3.1 中有两个不同的 ASP.NET Core Identity 重载,第一个版本名为 DefaultIdentity,您没有机会同时设置 User 和 Roles,因此语法看起来像
services.AddDefaultIdentity<IdentityUser>(options => ...
身份的第二个版本使用用户和角色,看起来像
services.AddIdentity<IdentityUser, IdentityRole>(options => ...
这是不同版本的身份,第一个包含 IdentityUI,第二个不包含 IdentityUI。 但是,如果您将角色服务添加为
,您可以将角色包含到第一个版本中services.AddDefaultIdentity<IdentityUser>(options =>...).AddRoles<IdentityRole>()...
如果您已将角色服务包含到您的服务集中,您可以将角色注入到 Configure 方法中,如
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DbContextOptions<ApplicationDbContext> identityDbContextOptions, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
如果您注入
,通常会出现此错误消息RoleManager<IdentityRole> roleManager
在项目的任何地方,无需添加 IdentityRole 服务(通过第一种或第二种方式)。
在startup.cs
文件中,您必须在其中一项服务中添加.addRoles<IdentityRole>()
:
services.AddDefaultIdentity<Usuarios>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>() //Line that can help you
.AddEntityFrameworkStores<ApplicationDbContext>();
在Net Core 3.1中,您需要为身份服务配置辅助函数。为此,您需要创建一个新实例 Microsoft.AspNetCore.Identity.IdentityBuilder.To activate RoleManager service -
- 转到您的 startup.cs 文件。
- 在我的例子中,语法看起来像 -
var builder = services.AddIdentityCore<AppUser>(); builder.AddRoles<IdentityRole>() .AddEntityFrameworkStores<AppIdentityDbContext>();