如何在Asp.Net Core Razor View中获得索赔 [英] How to get claim inside Asp.Net Core Razor View

查看:94
本文介绍了如何在Asp.Net Core Razor View中获得索赔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在rc1项目中做到了,

I did it in my rc1 project like:

User.Claims.ElementAt(#).Value

但是当我切换到rtm后,它将不再起作用.当我调试Razor视图时,对象看起来相同,但User.Claims只是空的.不知道原因可能是什么.

But after I switched to rtm it wouldn’t work anymore. When I debug the Razor view the object looks the same but User.Claims is just empty. Any idea what the reason could be.

推荐答案

假定您对当前的委托人有要求.在您的Razor视图中:

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

@((ClaimsIdentity) User.Identity)

这将使您可以访问当前用户的ClaimsIdentity.为了使您的索赔索取清晰,您可能需要创建一种扩展方法来搜索索赔.

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")

希望这会有所帮助.

在razor视图中快速搜索索赔身份也提出了类似的问题和答案: MVC 5访问声明身份用户数据

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

这篇关于如何在Asp.Net Core Razor View中获得索赔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆