`Store does not implement IUserRoleStore.` error with custom UserManager

526 views Asked by At

I'm using ASP.NET Core 2.1.2. I need create an application with login without Entity Framework. Anything ok but I have a problem when I want AddToRoleAsync.

This is my code:

[Authorize]
[Route("[controller]/[action]")]
public class AccountController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly IEmailSender _emailSender;
    private readonly ILogger _logger;

    public AccountController(
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        IEmailSender emailSender,
        ILogger<AccountController> logger)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _emailSender = emailSender;
        _logger = logger;
    }

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        ViewData["ReturnUrl"] = returnUrl;

        if (ModelState.IsValid)
        {
            var x = await _userManager.CreateAsync(user, model.Password);
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.PasswordMd5, model.RememberMe, lockoutOnFailure: false);   

            await _userManager.AddToRoleAsync(user, "Admin");

            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in.");
                return RedirectToLocal(returnUrl);
            }

            if (result.RequiresTwoFactor)
            {
                return RedirectToAction(nameof(LoginWith2fa), new { returnUrl, model.RememberMe });
            }

            if (result.IsLockedOut)
            {
                _logger.LogWarning("User account locked out.");
                return RedirectToAction(nameof(Lockout));
            }
            else
            {
                ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                return View(model);
            }
        }

        return View(model);
    }
}

I get this error:

System.NotSupportedException: Store does not implement IUserRoleStore.

at Microsoft.AspNetCore.Identity.UserManager1.GetUserRoleStore() at Microsoft.AspNetCore.Identity.UserManager1.d__106.MoveNext()
End of stack trace from previous location where exception was thrown

How can I add AddToRoleAsync without Entity Framework?

0

There are 0 answers