Reputation: 46322
I am adding a user to a role as follows (note that I run the code shown below on my machine):
Roles.AddUserToRole(oMU.UserName, "Role1");
With the following code I check to see if the user is in the role:
if (Roles.IsUserInRole(txtUserName.Text.Trim(), "Role1"))
and the user is indeed in the role.
I run the following to check if the current logged in user is in Role1 but it fails to enter the if statement - WHY? :
if (User.IsUserInRole("Role1"))
{
// does not enter this code
}
Upvotes: 3
Views: 6352
Reputation: 62301
You cannot call Roles.IsUserInRole("Role1")
as soon as user is assigned to a role like this -
Roles.AddUserToRole(oMU.UserName, "Role1");
IPrincipal object is injected to HttpContext.Current.User
on Application_AuthenticateRequest
only.
Therefore, you'll have to wait for next request in order to access Roles.IsUserInRole("Role1")
.
Make sure cacheRolesInCookie
is set to false, because it has some issues.
<roleManager enabled="true" cacheRolesInCookie="false"
defaultProvider="DefaultRoleProvider">
....
</roleManager>
Upvotes: 2
Reputation: 1265
I believe it should be User.IsInRole
instead of Roles.IsUserInRole
, or specifically specify the username as a parameter by passing Roles.IsUserInRole(User.Identity.Name,"Role1")
Roles.IsUserInRole, with one parameter, calls GetCurrentUser() for the username which will pull it from the CurrentPrincipal. It sounds like it your currently logged in user is different from that on the current principal.
Upvotes: 0