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

查看:28
本文介绍了如何在 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")

希望这会有所帮助.

在剃刀视图中快速搜索声明身份得出了一个类似的问题和答案: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天全站免登陆