如何获得内部Asp.Net核心Razor视图

问题描述:

要求我做到了像我RC1项目:如何获得内部Asp.Net核心Razor视图

User.Claims.ElementAt(#).Value 

但经过我切换到RTM将不再工作。当我调试Razor视图时,该对象看起来相同,但User.Claims只是空的。任何想法可能是什么原因。

+0

我发现这个问题。我在设置cookie的行中存在拼写错误:HttpContext.Authentication.SignInAsync(“typo here”,new ClaimsPrincipal(auth));.对不必要的工作人员抱歉。 – Sknecht

+0

只是一个建议,它可能是一个坏主意,索引索引索引..可能要使用索赔类型,如在JDupont的答案。 – juunas

+1

你说得对,一旦我们从系统中删除了一项索赔,它就已经导致出界。这已经是董事会的一项任务,但并没有围绕这个任务展开。 – Sknecht

假设您对当前的委托人附有索赔。在您的剃刀视图中:

@((ClaimsIdentity) User.Identity) 

这会让您访问当前用户的ClaimsIdentity。为了让您的索赔保持干净,您可能需要创建搜索索赔的扩展方法。

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; 
} 

然后,你可以访问你想要的任何索赔:

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

希望这有助于。

在Razor视图声明身份快速搜索想出了一个类似的问题和答案: MVC 5 Access Claims Identity User Data