Thay đổi tên người dùng không được nhà cung cấp thành viên sql hỗ trợ trong ASP.NET 2.0. Bạn vẫn có thể thay đổi tên người dùng nhưng bạn phải sử dụng triển khai tùy chỉnh.
Ngoài ra, bạn phải cập nhật cookie thành viên bằng tên người dùng mới để tránh việc giải trí của người dùng có cùng tên người dùng nhưng UserId mới.
Trong ví dụ bên dưới, tôi sử dụng LINQ to SQL để cập nhật bảng thành viên - Tôi có bối cảnh dữ liệu được gọi là MembershipDataContext.
public bool ChangeUserName(Guid userId, string newUserName)
{
bool success = false;
newUserName = newUserName.Trim();
// Make sure there is no user with the new username
if (Membership.GetUser(newUserName) == null)
{
MembershipUser u = Membership.GetUser(userId);
string oldUsername = u.UserName;
// get current application
MembershipDataContext context = new MembershipDataContext();
aspnet_User userToChange = (from user in context.aspnet_Users
where user.UserId == userId
select user).FirstOrDefault();
if (userToChange != null)
{
userToChange.UserName = newUserName;
userToChange.LoweredUserName = newUserName.ToLower();
context.SubmitChanges();
// ASP.NET Issues a cookie with the user name.
// When a request is made with the specified cookie,
// ASP.NET creates a row in aspnet_users table.
// To prevent this sign out the user and then sign it in
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie =
HttpContext.Current.Request.Cookies[cookieName];
FormsAuthenticationTicket authTicket = null;
try
{
authTicket =
FormsAuthentication.Decrypt(authCookie.Value);
FormsIdentity formsIdentity =
new FormsIdentity(
new FormsAuthenticationTicket(
authTicket.Version,
newUserName,
authTicket.IssueDate,
authTicket.Expiration,
authTicket.IsPersistent,
authTicket.UserData));
string y = HttpContext.Current.User.Identity.Name;
string[] roles =
authTicket.UserData.Split(new char[] { '|' });
System.Security.Principal.GenericPrincipal genericPrincipal =
new System.Security.Principal.GenericPrincipal(
formsIdentity,
roles);
HttpContext.Current.User = genericPrincipal;
}
catch (ArgumentException ex)
{
// Handle exceptions
}
catch(NullReferenceException ex)
{
// Handle exceptions
}
FormsAuthentication.SignOut();
HttpContext.Current.Session.Abandon();
FormsAuthentication.SetAuthCookie(newUserName, false);
success = true;
}
}
return success;
}
Nguồn
2010-01-28 09:08:39
tôi đã làm việc này có vẻ như vấn đề phải làm với việc gán vai trò cho đối tượng thành viên cũ cho tên người dùng cũ không tồn tại. do đó, một hàng vai trò mới được thêm tự động và một userid được tạo bởi các lớp vai trò. – zsharp
Vì vậy, bạn đã làm gì để giải quyết vấn đề? – CompanyDroneFromSector7G