@Roles.GetRolesForUser()
in razor layout view is not returning roles. @Roles.GetRolesForUser().Count()
is 0.
While @Roles.IsUserInRole('name_of_logged_in_role')
returns true
in the same view at the same place.
Razor View:
<p>
@User.Identity.Name //Output: MyName
@Roles.GetRolesForUser().Count() //Output: 0
@Roles.IsUserInRole("Radiologist") //Output: True
</p>
Update
@Roles.GetRolesForUser(User.Identity.Name).Length //Output: 0
@Roles.GetRolesForUser(User.Identity.GetUserName()).Length //Output: 0
After extensive research, I finally found the problem. I was able to reproduce the issue in a web application. Apparently, you cannot combine ASP.NET Identity with Simple Membership, simply like you did so with the GetRolesForUser
method. The Roles
object is by default setup for Simple Membership using a default provider, but it seems like your using ASP.NET Identity not Simple Membership. I didn't even notice the difference until I was wondering myself why it wasnt working.
The reason why you got string[0]
is because GetRolesForUser
executed an sql query to a table that doesnt exist in your database.
The reason why IsUserInRole
worked was more or less it did not even use the default provider to check it used the CacheRolesInCookie
If CacheRolesInCookie is true, then roleName may be checked against the roles cache rather than the specified role provider.
So, technically it went to a connectionString that was listed by the default provider and return string[0]
because you have no data in the database with that connectionString. Adding your current database to the providers would not help either because Simple Membership database schema is different from ASP.NET Identity
That being said, you should get the roles by UserName like this:
Simple Solution:
public List<string> GetRoles(string UserName)
{ List<string> roles = new List<string>();
if (!string.IsNullOrWhiteSpace(UserName))
{
ApplicationUser user = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
var account = new AccountController();
roles = account.UserManager.GetRoles(user.Id);
}
return roles;
}
Updated
Extended Solution:
You could extend the ASP.NET Identity Roles in your context
http://www.codeproject.com/Articles/799571/ASP-NET-MVC-Extending-ASP-NET-Identity-Roles