2016-08-18 7 views
1

簡単に言えば、私はIDを使用しています。私の解決策では、うまく機能しているカスタムアカウント設定ページを作成しました。問題は私がユーザFirstNameLastName_Layout.cshtmlに持っていることです。ユーザーは自分のプロフィールに行くと自分の名前を更新するまで、この方法では、素晴らしい作品ASP.NET IDが更新されたクレームを保存していません

public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper) 
    { 
     string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty; 

     var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal; 
     var nameClaim = identity?.FindFirst("fullname"); 


     if (nameClaim != null) 
     { 
      fullName = nameClaim.Value; 
     } 

     return MvcHtmlString.Create(fullName); 
    } 

:名前は私が持っているカスタムヘルパーメソッドによって設定されます。彼らはGeorgeからBobに自分の名前を変更した場合、彼らは私のウェブサイト上で回るとき、彼らはログアウトして再度ログインするまで、このメソッドはまだGeorgeとして自分の名前を引っ張る。

彼らはを更新するときに、私はそれを修正するためにやったことでした私は彼らの古いfullName主張を削除し、新しいものを追加し、このようにいくつかのコードを追加したアカウント設定で名前:

   var identity = User.Identity as ClaimsIdentity; 

       // check for existing claim and remove it 
       var currentClaim = identity.FindFirst("fullName"); 
       if (currentClaim != null) 
        identity.RemoveClaim(existingClaim); 

       // add new claim 
       var fullName = user.FirstName + " " + user.LastName; 

       identity.AddClaim(new Claim("fullName", fullName)); 

このコードのビットで_Layoutビューは現在、私たちの前の例では(名前を更新しGeorge今度はBobに変更されます)。 しかし、そのビューからウェブサイトの別の場所にクリックした瞬間やページを更新する瞬間には、すぐにGeorgeに変更されます。

まだ少し新人である私は、この新しい更新された主張が、別のページをクリックしたり更新したりしてからうまくいかない理由を戸惑います。どんな助けもありがとうございます。 :)

+2

あなただけの再発行できクッキー – tmg

答えて

0

解決策が見つかりました。私は、私もこれを行うために必要な新たな請求を追加したとき:

var authenticationManager = HttpContext.GetOwinContext().Authentication; 
    authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true }); 

だから、新しい完全なコードブロックは次のとおりです。

public static MvcHtmlString GetUsersFirstAndLastName(this HtmlHelper helper) 
    { 
     string fullName = HttpContext.Current?.User?.Identity?.Name ?? string.Empty; 

    var userIdentity = (ClaimsPrincipal)Thread.CurrentPrincipal; 
    var nameClaim = identity?.FindFirst("fullname"); 

    var authenticationManager = HttpContext.GetOwinContext().Authentication; 
    authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant(new ClaimsPrincipal(identity), new AuthenticationProperties() { IsPersistent = true }); 

    if (nameClaim != null) 
     { 
      fullName = nameClaim.Value; 
     } 

     return MvcHtmlString.Create(fullName); 
    } 
関連する問題