[英]How to get Role Claims in asp.net core 6 web api?
I try to get RoleClaims
from ASP.NET CORE Identity and my code is:我尝试从 ASP.NET CORE Identity 获取
RoleClaims
,我的代码是:
[HttpGet]
public async Task<IActionResult> GetAllRoleClaims(string email)
{
var user = await _userManager.FindByEmailAsync(email);
var role= await _userManager.GetRolesAsync(user);
var roleclaim = await _roleManager.GetClaimsAsync(role);
// var roleclaim = await _roleManager.GetClaimsAsync((IdentityRole)role);
return Ok(roleclaim);
}
It give me the error:它给我错误:
cannot convert from 'System.Collections.Generic.IList' to 'Microsoft.AspNetCore.Identity.IdentityRole'
无法从“System.Collections.Generic.IList”转换为“Microsoft.AspNetCore.Identity.IdentityRole”
the Error is at this section:错误在这一部分:
var roleclaim = _roleManager.GetClaimsAsync(role);
The GetClaimsAsync(role)
function does not accept the role
and give the above error and when I use this var roleclaim = _roleManager.GetClaimsAsync((IdentityRole)role);
GetClaimsAsync(role)
function 不接受该role
并出现上述错误,当我使用此var roleclaim = _roleManager.GetClaimsAsync((IdentityRole)role);
for conversion it gives me another error at runtime:对于转换,它在运行时给我另一个错误:
Unable to cast object of type 'System.Collections.Generic.List`1[System.String]' to type 'Microsoft.AspNetCore.Identity.IdentityRole'.
无法将类型为“System.Collections.Generic.List`1[System.String]”的 object 转换为类型“Microsoft.AspNetCore.Identity.IdentityRole”。
Can anyone help me how to getRoleClaims
from .net core Identity using roleManager
?谁能帮助我如何使用
getRoleClaims
从 .net core Identity roleManager
?
In your code,在你的代码中,
var role= await _userManager.GetRolesAsync(user);
Returns a list of role names (strings), eg ["admin", "user"].返回角色名称(字符串)列表,例如 ["admin", "user"]。
Now, use the role name (string) to get the role object if your user only has one role,现在,如果您的用户只有一个角色,则使用角色名称(字符串)获取角色 object,
var role = await _roleManager.FindByNameAsync(role.First());
Then, pass the role to get the claims,然后,传递角色以获取声明,
var roleclaim = _roleManager.GetClaimsAsync(role);
As per your scenario you can do as following: Therefore, it will return you the required claim.根据您的情况,您可以执行以下操作: 因此,它将返回给您所需的索赔。
[HttpGet]
public async Task<IActionResult> GetAllRoleClaims(string email)
{
var user = await _userManager.FindByEmailAsync(email);
var roleclaim = await _userManager.GetClaimsAsync(user);
return Ok(roleclaim);
}
Note: If you want to get only single claim by given email, in this scenario its better to skip looping and above way would be efficient in regards of Big O
.注意:如果你只想通过给定的 email 获得单一声明,在这种情况下最好跳过循环,并且以上方法对于
Big O
来说是有效的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.