Search code examples
c#model-view-controllerrolesuser-roles

Get UserName within Login to check if it's Administrator Role


I have a little problem. I'd like to check if the user is in role admin after clicking login. I have one problem left when doing it with

if(User.IsInRole("Administrator"))

User == null and i can't figure out another way to do it.

I tried several things but nothing actually works.

It should be withing this

 switch (result)
        {
            case SignInStatus.Success:
                //check if user is admin
                if (Roles.GetRolesForUser().Contains("Administrator"))
                {
                    return RedirectToAction("Index", "MIS");
                }
                else
                    return View();

Solution

  • Not sure why you're no longer getting access to the Http Context User object so here is a workaround

     switch (result)
               {
                   case SignInStatus.Success:
                       //check if user is admin
                       var adminRole = context.Roles.Where(r => r.Name == "Administrator").FirstOrDefault();
                       var user = context.Users.Where(u => u.UserName == model.Username).FirstOrDefault();
                       if(user.Roles.Where(r => r.RoleId == adminRole.Id).Count() > 0)
                       {
                           return RedirectToAction("Index", "MIS");
                       }
                       else
                           return View();