gpt4 book ai didi

c# - 在 MVC 5 的 Controller 中访问声明值

转载 作者:IT王子 更新时间:2023-10-29 03:53:35 25 4
gpt4 key购买 nike

我在我的应用程序中使用了 OWIN 身份验证。

登录操作

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, result.UserFirstName));
claims.Add(new Claim(ClaimTypes.Sid, result.UserID.ToString()));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

我想通过不同的操作访问 UserName 和 UserID。我如何访问声明中添加的值?

更新我试过了

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, result.UserFirstName + " " + result.UserLastName));
claims.Add(new Claim(ClaimTypes.Sid, result.UserIDNumber.ToString()));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var authenticationManager = Request.GetOwinContext().Authentication;
authenticationManager.SignIn(identity);

var claimsPrincipal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = claimsPrincipal;

enter image description here

我可以在快速窗口中查看值。但即使我无法访问该值。如何获取值?

最佳答案

您需要在登录后设置您的Thread.CurrentPrincipal

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, result.UserFirstName));
claims.Add(new Claim(ClaimTypes.Sid, result.UserID.ToString()));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
var claimsPrincipal = new ClaimsPrincipal(identity);
// Set current principal
Thread.CurrentPrincipal = claimsPrincipal;

然后以下将检索值。

//Get the current claims principal
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

// Get the claims values
var name = identity.Claims.Where(c => c.Type == ClaimTypes.Name)
.Select(c => c.Value).SingleOrDefault();
var sid = identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
.Select(c => c.Value).SingleOrDefault();

关于c# - 在 MVC 5 的 Controller 中访问声明值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22246538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com