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.