54 69 6d
54 69 6d

Reputation: 165

Route user to correct area

When a user logs in. I'm looking for a way to route a user to the correct area based on their role in identity.

I've tried:

Thanks ahead for the ideas!

Upvotes: 0

Views: 585

Answers (1)

Ryan
Ryan

Reputation: 20116

If you are using asp.net core identity,in controller, you could directly use var isInRole = User.IsInRole("Admin") to check whether current user has an Admin role.

Or use UserManager to get current user and all his roles:

private readonly UserManager<IdentityUser> _userManager;
public HomeController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

[Authorize(Roles = "Admin")]
public async Task<IActionResult> TestView()
{
    var user = await _userManager.GetUserAsync(HttpContext.User);

    var roles = await _userManager.GetRolesAsync(user);

    var matchingvalues = roles.SingleOrDefault(stringToCheck => stringToCheck.Equals("Admin"));
    if(matchingvalues != null)
    {
        return RedirectToAction("Index", "Dashboard", new { area = "Admin" });
    }

    return View();
}

Upvotes: 1

Related Questions