【问题标题】:Unable to resolve service for type 'Microsoft.AspNetCore.Identity.UserManager' while attempting to activate 'Management.Controllers.RoleController'尝试激活“Management.Controllers.RoleController”时无法解析“Microsoft.AspNetCore.Identity.UserManager”类型的服务
【发布时间】:2021-08-07 14:39:49
【问题描述】:

我想创建角色并将用户分配给这些角色,我已经创建了角色但我不知道如何将用户分配给他们,我尝试在启动时将 UserManager 添加到服务但它不起作用。我有这个错误:

InvalidOperationException:尝试激活“PFE_Management.Controllers.RoleController”时无法解析“Microsoft.AspNetCore.Identity.UserManager`1[PFE_Management.Models.AppUser]”类型的服务。

这是控制器:

namespace PFE_Management.Controllers
{
    public class RoleController : Controller
    {
        private RoleManager<IdentityRole> roleManager;
        private UserManager<AppUser> userManager;
        public RoleController(RoleManager<IdentityRole> roleMgr, UserManager<AppUser> userMrg)
        {
            roleManager = roleMgr;
            userManager = userMrg;
        }

        //some code here
        // le code qui suive c'est ajouter ou supprimer un utilisateur pour un Role
        public async Task<IActionResult> Update(string id)
        {
            //some code here
        }
        [HttpPost]
        public async Task<IActionResult> Update(RoleModification model)
        {
            IdentityResult result;
            if (ModelState.IsValid)
            {
                foreach (string userId in model.AddIds ?? new string[] { })
                {
                    AppUser user = await userManager.FindByIdAsync(userId);
                    if (user != null)
                    {
                        result = await userManager.AddToRoleAsync(user, model.RoleName);
                        if (!result.Succeeded)
                            Errors(result);
                    }
                }
                foreach (string userId in model.DeleteIds ?? new string[] { })
                {
                    AppUser user = await userManager.FindByIdAsync(userId);
                    if (user != null)
                    {
                        result = await userManager.RemoveFromRoleAsync(user, model.RoleName);
                        if (!result.Succeeded)
                            Errors(result);
                    }
                }
            }

            if (ModelState.IsValid)
                return RedirectToAction(nameof(Index));
            else
                return await Update(model.RoleId);
        }
    }
}

这是 startup.cs 中的服务:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)                
            .AddRoles<IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddControllersWithViews();
        services.AddRazorPages();    
    }

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc asp.net-core-identity


    【解决方案1】:

    AddDefaultIdentity 不会将用户管理器添加到服务集合中。您需要自己添加。例如:

    services.AddDefaultIdentity<IdentityUser>(...)                
        .AddRoles<IdentityRole>()
        .AddUserManager<IdentityUser>() // <-- add this
        .AddEntityFrameworkStores<ApplicationDbContext>();
    

    【讨论】:

    • 类型 IdentityUser 必须派生自 UserManager
    • AddDefaultIdentity 已经注册了UserManager,所以我认为这里真正的问题是对AddDefaultIdentity 的调用应该只使用AppUser 而不是IdentityUser
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2019-05-20
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多