2010-01-26 2 views
5

asp.net 멤버십 사용자 테이블에 직접 액세스하여 사용자 이름을 변경할 수 있습니다. 그러나 이전 사용자 이름은 새 행에 보존되고 asp.net에 의해 자동으로 새 사용자 ID가 지정됩니다. 어떻게 그 일을 막을 수 있습니까?Asp.Net 회원에서 수동으로 사용자 이름을 변경하십시오.

편집 : 회원 테이블이 아닌 사용자 테이블과 역할 테이블에서만 수정 :

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 
{ 
    ... 
} 
+0

나는 문제가 문제가 사용자가 이전 멤버 이름에 대한 기존 멤버십 개체에 역할을 할당하는 것과 관련이 있다는 것을 알게되었습니다. 새 역할 행이 자동으로 추가되고 역할 클래스가 작성한 사용자 ID가 추가됩니다. – zsharp

+0

그럼 문제를 해결하기 위해 무엇을 했습니까? – CompanyDroneFromSector7G

답변

0

사용자 이름을 어떻게 변경 했습니까? 방금 업데이트 SQL 문을 사용하여 새 행을 만들거나 이전 사용자 이름을 유지하지 않고 사용자 이름을 업데이트했습니다.

UPDATE [MyDatabase].[dbo].[aspnet_Users] 
SET [UserName] = 'mynewusername', 
    [LoweredUserName] = LOWER('mynewusername') 
WHERE [UserName] = 'myusername' 
+0

SQL에 대한 링크를 사용하여 – zsharp

+0

자세한 내용을 제공하십시오 .. 문제는 당신이 업데이 트를 수행하는 데 사용 linq 쿼리에있을 수 있습니다. 위의 sql 코드는 새 레코드를 만들지 않고 사용자 이름 필드를 업데이트합니다. –

+0

위를 참조하십시오. 나는 또한 SQL 문과 같은 결과로 도망 갔다. – zsharp

1

당신은 모두 사용자 이름을 변경해야하고 LoweredUserName ... 나는 API가 다른 필드를 사용하는 조회를 한 (하나가 변경 되었기 때문에) 레코드가 존재하지 않았다 관찰 가정, 새로운 창조 하나. 일반적으로 이전 레코드는 보존하지 않습니다.

EDIT : 또한 ProviderUserKey 필드로 계정을 조회 할 수 있습니까?

+0

나는 둘 다 바꿨다. 새 사용자 이름이 제대로 작동하지만 테이블에 이전 이름에 대한 행이 추가됩니다. (회원 테이블이 아닌 사용자 테이블과 역할 테이블에만 해당) – zsharp

+0

사용자 ID로 검색합니다 – zsharp

+0

쿼리하는 provideruserkey 필드가 문제일까요? 또한 SingleOrDefault를 사용하여 왜 null 체크를하지 않습니까? –

10

ASP.NET 2.0의 sql 멤버 자격 공급자는 사용자 이름을 변경할 수 없습니다. 사용자 이름을 변경할 수는 있지만 사용자 정의 구현을 사용해야합니다.

동일한 사용자 이름이지만 새로운 UserId로 사용자를 다시 만들지 않으려면 회원 쿠키를 새 사용자 이름으로 업데이트해야합니다.

아래 예제에서는 Linq를 사용하여 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; 
} 
+0

FormsAuthentication.setauthcookie를 사용할 때 생성 된 쿠키가 아닙니까? 왜 수동으로 만들었습니까? – zsharp

+0

쿠키를 수동으로 설정하지 않습니다. 쿠키를 사용하여 FormsAuthenticationTicket의 인스턴스를 가져옵니다. –

+0

내 요점은 내가 티켓의 인스턴스를 가져와야하는 이유를 이해하지 못한다는 것입니다. 그냥 서명하고 다시 로그인하면 충분하지 않을까요? – zsharp

관련 문제