MVC 5 控制器中的访问声明值 [英] Access Claim values in controller in MVC 5

查看:16
本文介绍了MVC 5 控制器中的访问声明值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have used OWIN authentication in my application.

登录操作

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);

我想从不同的操作访问用户名和用户 ID.如何访问声明中添加的值?

I want to access the UserName and UserID from different action. How can I access the values which is added in the claims?

更新我试过了

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;

我可以查看快速窗口内的值.但即使我无法访问该值.如何获取价值?

I can view the values inside the quick window. But even though I couldn't access the value. How to get the value?

推荐答案

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

You need to set your Thread.CurrentPrincipal after login i.e.

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();

这篇关于MVC 5 控制器中的访问声明值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆