Reputation: 165
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:
return RedirectToAction("Index", "Dashboard", new { area = "Admin" });
,
but I have multiple roles.@if (User.Identity.IsAuthenticated && User.IsInRole("Admin")) else if()
. Then used <text>
and <script>
tags in between the if statements to call a function that would redirect the user. It didn't provide an error, just didn't work. I figured it wouldn't, but... trying to think outside the boxThanks ahead for the ideas!
Upvotes: 0
Views: 585
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