在MVC 5访问索赔值控制器 [英] Access Claim values in controller in MVC 5

查看:216
本文介绍了在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;

那么下面将检索的值。

Then the following will retrieve the values.

//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天全站免登陆