开发者

GetRolesForUser tries to get Roles on old username?

I have a section on a page where a user can change their username. This is basically the code for that:

user.UserName = txtNewUserName.Text;
user.Save();

user is a class in my dbml and Save calls SubmitChanges on the data context.

The name is changed in the database, so when it calls the following method, it fails because it is trying to get the user with the old username instead of the one that is in the database now.

public override string[] GetRolesForUser(string username)
{
    return dc.Users.Where(u => u.UserName== username)
                   .SingleOrDefault().Roles
                   .Select(r => r.RoleNam开发者_运维问答e).ToArray<string>();
}


It looks as you keep the dc used in GetRolesForUser around for some time. So if you have retrived the user before and then request the same user again, using the same data context it will return the user cached by that data context.

Try using

public override string[] GetRolesForUser(string username)
{
    using (var ctx = new MyDataContext()) {
        return ctx.Users.Where(u => u.UserName== username)
                        .SingleOrDefault().Roles
                        .Select(r => r.RoleName).ToArray<string>();
    }
}

Edit

Well if the username parameter holds the old user name, the function you provided works correctly in not returning any roles for the old user ... make sure that you pass the new username into the function. I.e. it is a problem of where you hold the value that gets passed into the funcion, and not a problem of the function.

2nd Edit (After knowing that a RoleProvider is used)

Saving the user to the database does not alter the credentials of the current user. These are set during login. To verify cou can check whether HttpContext.User still holds the user name. So what you need to do is to either force the uer to log in again, or use an imutable indentifier as the credential, e.g. a guid assigned to each user, then the user name can change and the roles still can be resolved.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜