[英]Get an item from List<Claim> in ASP.NET Web API
I am creating a list of claims while login:我在登录时创建了一个声明列表:
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim("Testing", "test")
};
There is no authorisation for the Login method so the claims have not been saved or the cookie hasn't been created but the list contains the userId created and I want to save it in an activity log (table): Login 方法没有授权,因此尚未保存声明或尚未创建 cookie,但列表包含创建的 userId,我想将其保存在活动日志(表)中:
var activityLog = new AccessLogEntity
{
ActivityDate = DateTime.UtcNow,
UserId = ## get from claims (List<Claim>
};
await _context.tbl_ActivityLogs.AddAsync(activityLog);
await _context.SaveChangesAsync();
How can I achieve this?我怎样才能做到这一点?
(I didn't fully understand the question or maybe I didn't understand it at all.) (我没有完全理解这个问题,或者我根本没有理解。)
I have never used Claims or ASP.NET core.我从未使用过 Claims 或 ASP.NET 内核。 However, if the second parameter in your constructor is the UserId you want to get, as in
但是,如果构造函数中的第二个参数是您想要获取的 UserId,如
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, /* -----> */ user.UserName /*<------ this one here */ ) ,
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim("Testing", /* -----> */"test"/* <----- Or this */)
};
You can easily do that with你可以很容易地做到这一点
claims[0 /* Or whichever you want to get*/].Value;
Full code完整代码
var activityLog = new AccessLogEntity
{
ActivityDate = DateTime.UtcNow,
UserId = claims[i /*Or whatever*/].Value;
};
await _context.tbl_ActivityLogs.AddAsync(activityLog);
await _context.SaveChangesAsync();
Edit:编辑:
If you don't want to hardcode an index but rather get the username from the name identifier, use something like this:如果您不想硬编码索引,而是从名称标识符中获取用户名,请使用以下内容:
public string getUsernameFromID(List<Claim> claims, string id)
{
foreach (var cl in claims)
{
if (cl.Type == id)
{
return cl.Value;
}
}
return "";
}
Use it like:像这样使用它:
getUsernameFromID(claims, "Testing"); // Which returns "test"
which in this case will return "test" and it indeed does!在这种情况下,它会返回“test”,而且确实如此!
Am I missing something here???我在这里错过了什么吗??? I am pretty sure I didn't get your question...
我很确定我没有得到你的问题...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.