0

This is my first time using RoleManager, and I am having a problem adding a username to a role. The goal is to check if the user (who is currently logging in) is an admin or not (isAdmin = 1 in SQL database). What I am using in my LoginController is:

var usr = db.Users.Where(u => u.UserName.ToLower() == userLogin.UserName.ToLower() && 
u.Password.Equals(userLogin.Password, StringComparison.Ordinal)).FirstOrDefault();

if (usr != null)
{
   FormsAuthentication.SetAuthCookie(usr.UserName, false);
   if (usr.IsAdmin == true)
   {
      if(!Roles.RoleExists("Admin"))
           Roles.CreateRole("Admin");
           var x = Roles.GetAllRoles();
           if(!Roles.IsUserInRole(usr.UserName, "Admin"))
               Roles.AddUserToRole(usr.UserName, "Admin");
    }
    return RedirectToAction("Index", "Home");
}

I set breakpoints in each of these lines, and Roles.CreateRole("Admin"); is never reached, which would imply that there is a Role called "Admin". However, var x = Roles.GetAllRoles(); always shows null.

if(!Roles.IsUserInRole(usr.UserName, "Admin")) is always reached, so that user is currently not assigned to that role, but I get a ProviderException on the next line, with Additional Information of: "The user "_username" was not found.

My Web Config in case anybody needs it:

<roleManager enabled="true" defaultProvider="MyRoleProvider">
  <providers>
    <clear />
    <add name="MyRoleProvider" type="System.Web.Providers.DefaultRoleProvider" 
    connectionStringName="StoreFrontConnectionString" applicationName="/"/>
  </providers>
</roleManager>

Any help would be greatly appreciated.

vivek
  • 1,595
  • 2
  • 18
  • 35
bankey
  • 189
  • 12

1 Answers1

0

I've just worked around this problem myself and it might be that you're having the same problem.

In my case it was that my web.config was slightly wrong. Make sure that the applicationName parameter for your profile provider, membership provider and role manager is the same in each case. I had a typo in one of them and it meant that the user that looked as though it was there was actually for a different application, so when I called AddUserToRole it threw an exception.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
rpeh
  • 17
  • 4