How to get claim inside Asp.Net Core Razor View

前端 未结 3 592
名媛妹妹
名媛妹妹 2020-12-16 12:46

I did it in my rc1 project like:

User.Claims.ElementAt(#).Value

But after I switched to rtm it wouldn’t work anymore. When I debug the Razo

3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 13:42

    Assuming you have claims attached to the current principal. In your Razor view:

    @((ClaimsIdentity) User.Identity)
    

    This will give you access to the ClaimsIdentity of the current user. In an effort to keep your claims fetching clean you may want to create an extension method for searching claims.

    public static string GetSpecificClaim(this ClaimsIdentity claimsIdentity, string claimType)
    {
        var claim = claimsIdentity.Claims.FirstOrDefault(x => x.Type == claimType);
    
        return (claim != null) ? claim.Value : string.Empty;
    }
    

    Then you can just access whatever claim you want with:

    @((ClaimsIdentity) User.Identity).GetSpecificClaim("someclaimtype")
    

    Hope this helps.

    Quick search for claims identity in razor view came up with a similar question and answer: MVC 5 Access Claims Identity User Data

提交回复
热议问题