Re: Roles.IsUserInRole != Context.User.IsInRole



Thanks for Dominick's informative inputs.

Hi Lyndon,

As for the difference between Roles.IsUserInRole and
Context.User.IsInRole, it is due to the internal implementation of
Roles.IsUserInRole method.

As for "Context.User.IsInRole", it uses the Context.User class
instance(when you enable role manager, it is an instance of RolePrincipal
class), and this class will cache roles and the IsInRole method will search
cached roles first.

While for the "Roles" class, its "IsUserInRole" method has the following
code logic:

1) first check whether Thread.CurrentPrincipal is null, if not return this
principal

2) #1 != null, check whether the principal is of type "RolePrincipal" or
derived type and whether the current principal's provider equals the
configured provider, if match, the Thread.Principal object will be used for
check roles,(and this is the same as Context.User.IsInRole).

3) if #1 is null or #2 not match, it will use the underlying RoleProvider
to query the roles from backend database storage(e.g. SQL Server...)
instead of the RolePrincpal class


Here is the disassemblied code of the "Roles.IsUserInRole" from reflector

===================
................
IPrincipal principal1 = Roles.GetCurrentUser();
if (((principal1 != null) && (principal1 is RolePrincipal)) &&
((((RolePrincipal) principal1).ProviderName == Roles.Provider.Name) &&
StringUtil.EqualsIgnoreCase(username, principal1.Identity.Name)))
{
flag1 = principal1.IsInRole(roleName);
}
else
{
flag1 = Roles.Provider.IsUserInRole(username, roleName);
}

=====================

I think for your scenario, you have writen your custom role provider, does
it also use a custom Principal class(is it derived from RolePrincipal
class)? I think this maybe the cause why you get different result.

Anyway, if you have any further questions on this, please feel free to post
here.

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead



This posting is provided "AS IS" with no warranties, and confers no rights.


.