在.NET 2.0中的自定义角色提供程序(继承自RoleProvider)中,IsUserInRole方法已经过硬编码,始终返回true:
public override bool IsUserInRole(string username, string roleName) { return true; }
在配置为使用此角色提供程序的ASP.NET应用程序中,以下代码返回true(按预期方式):
Roles.IsUserInRole("any username", "any rolename"); // results in true
但是,以下代码返回false:
Roles.IsUserInRole("any rolename"); // results in false
请注意,User.IsInRole(“any rolename”)也返回false。
更新:请注意,对于采用单个字符串的版本,似乎没有可用的覆盖,这导致了我在#2中的假设。
答案 0 :(得分:3)
我在.net反射器中查看了Roles.IsUserInRole(string rolename),它解析为以下内容:
public static bool IsUserInRole(string roleName)
{
return IsUserInRole(GetCurrentUserName(), roleName);
}
我会看看你当前的用户。原因如下:
private static string GetCurrentUserName()
{
IPrincipal currentUser = GetCurrentUser();
if ((currentUser != null) && (currentUser.Identity != null))
{
return currentUser.Identity.Name;
}
return string.Empty;
}
我愿意打赌这会返回一个空字符串,因为您没有当前用户,或者其名称是空字符串或为空。
在IsUserInRole(string username, string roleName)
方法中,在开头附近有以下代码块:
if (username.Length < 1)
{
return false;
}
如果你的GetCurrentUserName()
没有返回任何有意义的内容,那么它会在调用被覆盖的方法之前返回false。
道德要脱离这一点:反射器是一个很棒的工具:)
答案 1 :(得分:0)
另请注意,您是否在RoleManager配置中选择了cacheRolesInCookie =“true”。如果您已向数据库添加了新角色,则可能正在查看cookie中的缓存版本。
我遇到了这个问题,解决方案是删除cookie并重新登录。
答案 2 :(得分:0)
这可能有助于某人 - 请注意:
如果您使用登录控件进行身份验证 - 输入到控件中的用户名将成为HlespContext.Current.User.Identity.Name,它在Roles.IsUserInRole(字符串rolename)中使用,更具体地说,是成员身份的GetUser( ) 方法。因此,如果是这种情况,请确保覆盖Authenticate事件,在此方法中验证用户并将用户名设置为您的自定义成员资格提供程序可以使用的值。
protected void crtlLoginUserLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
bool blnAuthenticate = false;
string strUserName = crtlLoginUserLogin.UserName;
if (IsValidEmail(strUserName))
{
//if more than one user has email address - must authenticate by username.
MembershipUserCollection users = Membership.FindUsersByEmail(strUserName);
if (users.Count > 1)
{
crtlLoginUserLogin.FailureText = "We are unable to determine which account is registered to that email address. Please enter your Username to login.";
}
else
{
strUserName = Membership.GetUserNameByEmail(strUserName);
blnAuthenticate = Membership.ValidateUser(strUserName, crtlLoginUserLogin.Password);
//setting the userLogin to the correct user name (only on successful authentication)
if (blnAuthenticate)
{
crtlLoginUserLogin.UserName = strUserName;
}
}
}
else
{
blnAuthenticate = Membership.ValidateUser(strUserName, crtlLoginUserLogin.Password);
}
e.Authenticated = blnAuthenticate;
}