ASP .Net 角色 - RemoveUserFromRole - 删除角色时出错
给定这段代码...(role
和 userName
是传入的字符串)
string[] existingRoles = Roles.GetRolesForUser(userName);
foreach (string role in existingRoles)
{
if (!newRoles.Contains(role))
{
Authentication.AuthTraceStatic("Removing user {0} from role: {1}",
userName, role);
Roles.RemoveUserFromRole(userName, role);
}
}
我收到以下错误:
用户“xxx”已不属于角色“yyy”。
这有点令人困惑,因为我刚刚获取了用户的角色并检查了我想要删除的角色是否存在......有什么线索可以让它正常工作吗?
Given this bit of code... (role
and userName
are strings passed in)
string[] existingRoles = Roles.GetRolesForUser(userName);
foreach (string role in existingRoles)
{
if (!newRoles.Contains(role))
{
Authentication.AuthTraceStatic("Removing user {0} from role: {1}",
userName, role);
Roles.RemoveUserFromRole(userName, role);
}
}
I get the following error:
The user 'xxx' is already not in role 'yyy'.
Which is somewhat mystifying given I have just fetched the user's roles and checked that the one I want to remove exists.... Any clues what to do get this to work correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不会是多线程的问题吧?您是否尝试过用锁块包围代码?如果在 foreach 循环中使用 Roles.IsUserInRole(username, role) 检查角色是否存在,会发生什么?
我会尝试用这样的代码来调试它,看看会发生什么。
Can't it be a multithreading issue? Have you tried to surround the code with a lock block? What happens if you check for the role existence using Roles.IsUserInRole(username, role) inside foreach loop?
I would try to debug it with a code like that, see what happens.
首先检查您的用户名的上下文。我自己也有同样的问题。有时,用户名会返回当前登录的用户,而不是您尝试删除其角色的用户。
其次,检查以确保您的代码不会删除您不期望的角色。这是我遇到同样错误时遇到的两个问题。还要确保您使用会员资格提供程序来获取会员资格用户对象,然后您可以使用该对象来访问用户名。
这是我的类似代码,但我循环遍历已绑定并预填充了用户已有的选定角色的角色复选框列表。
MembershipUser 用户 = Membership.GetUser( txtUserName.Text);
希望这有帮助。 GS
First Check the context of your user name. I had this same issue myself. Sometimes username is returning the currently logged in user and not the user you're trying to remove roles on.
Second, check to ensure your code isn't removing roles where you aren't expecting it to. These are the two issues I had when I got the same error. Also make sure you're using the membership provider to get the membership user object which you can then use to access the username.
Here's my similar code but I was looping through a checkbox list of roles that was already bound and prepopulated with the selected roles the user already has.
MembershipUser user = Membership.GetUser( txtUserName.Text);
Hope this helps. GS
答案是,我们在 dbo.aspnet_Roles 表上有 2 个角色条目,具有相同的 RoleName 和不同的 LoweredRolenames,这似乎导致删除代码默默失败。
The answer turned out to be that we had 2 entries on the dbo.aspnet_Roles table for the role, with the same RoleName different LoweredRolenames, which seems to lead to the removal code silently failing.