问题描述
我正在使用这段代码从 JWT 的声明中读取单个值。
return httpContext.User.Claims.Single(x => x.Type == "id").Value;
获取此声明的值:
"id": "b6dddcaa-dba6-49cf-ae2d-7e3a5d060553"
但是,我想读取具有多个值的键。 但使用相同的代码:
return httpContext.User.Claims.Single(x => x.Type == "groups").Value;
对于此声明:
"groups": [
"123","234"
],
我在逻辑上收到以下错误消息:
system.invalidOperationException: "Sequence contains more than one matching element"
我找不到相应的方法。有人可以帮我吗?
解决方法
return httpContext.User.Claims
.Where(x => x.Type == "groups") //Filter based on condition
.Select(y => y.Value); // get only Value
Single()
:它返回序列的单个特定元素。 如果找到多个满足条件的元素,则抛出错误
参考ClaimsPrincipal.FindAll(Predicate<Claim>)
检索与指定谓词匹配的所有声明。
IEnumerable<Claim> claims = httpContext.User.FindAll(x => x.Type == "groups");
IEnumerable<string> values = claims.Select(c => c.Value);
return values;