InvalidOperationException:无法解析类型为'Microsoft.AspNetCore.Identity.RoleManage的服务

时间:2019-04-04 01:22:44

标签: c# .net-core

我正在使用netCore 2.1,但遇到了这个问题:

处理请求时发生未处理的异常。

  

InvalidOperationException:无法解析类型的服务   'Microsoft.AspNetCore.Identity.RoleManager`1 [Microsoft.AspNetCore.Identity.IdentityRole]'   尝试激活时   'sistemaAC.Areas.Identity.Pages.Account.RegisterModel'。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

        public RegisterModel(
            UserManager<IdentityUser> userManager,
            SignInManager<IdentityUser> signInManager,
            ILogger<RegisterModel> logger,
            IEmailSender emailSender,
            RoleManager<IdentityRole> roleManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
            _emailSender = emailSender;
            _roleManager = roleManager;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public string ReturnUrl { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            [Display(Name = "Email")]
            public string Email { get; set; }

            [Required]
            [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)]
            [DataType(DataType.Password)]
            [Display(Name = "Password")]
            public string Password { get; set; }    
            [DataType(DataType.Password)]
            [Display(Name = "Confirm password")]
            [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
            public string ConfirmPassword { get; set; }
        }

        public void OnGet(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new IdentityUser { UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Password);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                        $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");


                    var xRol = await _roleManager.RoleExistsAsync("Administrador");
                    if(!xRol)
                    {
                        var role = new IdentityRole("Administrador");
                        var res = await _roleManager.CreateAsync(role);

                        if (res.Succeeded)
                        {
                            await _userManager.AddToRoleAsync(user, "Administrador");
                            await _signInManager.SignInAsync(user, isPersistent: false);

                        }
                    }
                    else
                    {
                        await _userManager.AddToRoleAsync(user, "Administrador");
                        await _signInManager.SignInAsync(user, isPersistent: false);
                    }

                    xRol = await _roleManager.RoleExistsAsync("Usuario");
                    if (!xRol)
                    {
                        var role = new IdentityRole();
                        role.Name = "Usuario";
                        await _roleManager.CreateAsync(role);
                    }

                    xRol = await _roleManager.RoleExistsAsync("Asistente");
                    if (!xRol)
                    {
                        var role = new IdentityRole();
                        role.Name = "Asistente";
                        await _roleManager.CreateAsync(role);

                    }
                    return LocalRedirect(returnUrl);


                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }   
            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我面临着同样的问题。我在此线程上找到了答案: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`

基于上述代码,我假设您使用了身份服务。生成的代码创建一个/Areas/Identity/IdentityHostingStartup.cs类。您需要更改代码行

services.AddDefaultIdentity<IdentityUser>

services.AddIdentity<IdentityUser,IdentityRole>

每个请求,这是我的完整AddIdentity代码

services.AddIdentity<IdentityUser,IdentityRole>(options =>
{
    //option settings...
})
.AddEntityFrameworkStores<IdentityDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();