我正在使用MembershipDataContext中的代码在我的 Web 表单代码后面的 aspnet_user 表中更改用户名。但它不起作用,因为找不到 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;
}