2016-02-07 124 views
2

我跟了一個SO回答這裏實現自定義聲明:自定義聲明沒有返回

How to extend available properties of User.Identity

不過,我的問題是,它永遠不會返回一個值。下面是我的實現:

using System.Security.Claims; 
using System.Security.Principal; 

namespace Events.Extensions 
{ 
    public static class IdentityExtensions 
    { 
     public static string GetCustomUrl(this IIdentity identity) 
     { 
      var claim = ((ClaimsIdentity)identity).FindFirst("CustomUrl"); 
      // Test for null to avoid issues during local testing 
      return (claim != null) ? claim.Value : string.Empty; 
     } 
    } 
} 

namespace Events.Models 
{ 
    public class Member : IdentityUser 
    { 
     public string CustomUrl { get; set; } 
     public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<Member> manager) 
     { 
      var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); 
      userIdentity.AddClaim(new Claim("CustomUrl", this.CustomUrl)); 
      return userIdentity; 
     } 
    } 
} 

現在我試着給它一個視圖來進行測試:

<script>alert(@User.Identity.GetCustomUrl());</script> 

值始終是什麼,但是如果我更改爲@User.Identity.GetUserId()那就還給我Id。

我錯過了某個步驟?

回答

1

它是一個字符串,所以你應該使用:alert('@User.Identity.GetCustomUrl()');請注意引號,因爲否則'javascript'用它返回的名稱搜索一個對象。如果它本身可能包含單引號,請不要忘記在此處避開此值。

+0

你在那個上是對的。但是,我現在想明白爲什麼這個聲明不起作用:'@ Html.ActionLink(「Manage my Profile」,「Show」,「Members」,new {id = @ User.Identity.GetCustomUrl()},新{title =「Manage」})'我試圖讓它產生一個'events/Members/Show/abc'鏈接 – Bojan

+0

實際上忽略了我以前的評論,出於某種原因,它突然開始工作,我想知道如果我只是有一個緩存問題。 – Bojan

+0

沒問題。很高興它解決了。 – Silvermind