I am using this code for login. How can I find a user role when user login?
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Username);
if (user != null)
{
if (!await UserManager.IsEmailConfirmedAsync(user.Id))
{
ViewBag.errorMessage = "You must have a confirmed email to log on.";
return View("Error");
}
}
var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
user.Roles
will fetch list of Roles user belong to. Based on your requirement you can do something like belowBased on our discussion if you want to fetch all the roles from database you need to do below
Add
ApplicationRoleManager
class to your IdentityConfig.cs as belowAssign RoleManager to Owin Context, so add below to starup.auth.cs
In AccountController.cs add a property
Pass it in the Constructor
Once you are done with this you can fetch list of all roles by using var roles = RoleManager.Roles;
You can use this as per your requirement.