[英]Changing the minimum UserName length in a custom ASP.NET Membership Provider?
[英]Manually changing username in Asp.Net Membership
我可以通過直接訪問asp.net成員資格用戶表來更改用戶名。 但是,舊用戶名保留在新行中,並由asp.net自動分配新的UserID。 我如何阻止這種情況發生?
編輯:僅在users表和角色表中,而不是在成員資格表中。
var mUser = dc.aspnet_Users
.Where(u => u.UserId == (Guid)user.ProviderUserKey)
.Select(u => u).SingleOrDefault();
mUser.UserName = newName;
mUser.LoweredUserName = newName.ToLower();
try
{
dc.SubmitChanges();
}
catch
{
...
}
ASP.NET 2.0中的sql成員資格提供程序不支持更改用戶名。 您仍然可以更改用戶名,但必須使用自定義實現。
此外,您必須使用新用戶名更新成員資格cookie,以避免使用相同的用戶名重新創建用戶,但需要使用新的UserId。
在下面的示例中,我使用Linq to SQL來更新成員資格表 - 我有名為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;
}
你必須改變UserName和LoweredUserName ...我假設API使用了另一個字段,進行了查找,觀察到記錄不存在(因為一個被更改),並創建了一個新的。 通常,它不會保留舊記錄。
編輯:問題也可能是你正在通過ProviderUserKey字段查找帳戶?
你是怎么改變用戶名的? 我只是通過使用更新sql語句並更新用戶名而不創建新行或保留舊用戶名。
UPDATE [MyDatabase].[dbo].[aspnet_Users]
SET [UserName] = 'mynewusername',
[LoweredUserName] = LOWER('mynewusername')
WHERE [UserName] = 'myusername'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.