Reputation: 1
I am working netCore 2.1 and I have this problem:
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 '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();
}
}
}
Upvotes: 0
Views: 1354
Reputation: 11
I was facing the same issue. I found the answer on this thread: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.RoleManager`
Based upon the code above, I assumed you scaffolded in the Identity services. The generated code creates a /Areas/Identity/IdentityHostingStartup.cs class. You need to change the line of code
services.AddDefaultIdentity<IdentityUser>
to
services.AddIdentity<IdentityUser,IdentityRole>
Per request, here is my full AddIdentity code
services.AddIdentity<IdentityUser,IdentityRole>(options =>
{
//option settings...
})
.AddEntityFrameworkStores<IdentityDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
Upvotes: 1