本文介绍了Mvc访问索赔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我可以登录机智索赔,但我无法访问索赔值。我只是访问名称值
Hi guys,
i can login wit claims but i can't access claim values. i just accessing "name" value
public ActionResult Login(UserModel model)
{
var userCheck = db.User.Where(u => u.Mail == model.Mail && u.Password == model.Password);
foreach (var item in userCheck)
{
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Sid, item.UserID.ToString()),
new Claim(ClaimTypes.Name, item.Name),
new Claim(ClaimTypes.Surname, item.Surname),
new Claim(ClaimTypes.Email, item.Mail)
},
"ApplicationCookie");
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
return Redirect(GetRedirectUrl(model.ReturnUrl));
}
return View(model);
}
Global.asax
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Sid;
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Surname;
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
}
[]
[]
我如何获取其他索赔值?
我尝试过:
.............................. .............................
Image - TinyPic - Free Image Hosting, Photo Sharing & Video Hosting[^]
Image - TinyPic - Free Image Hosting, Photo Sharing & Video Hosting[^]
how can i access other claim values ?
What I have tried:
...........................................................
推荐答案
public static class ClaimsExtensions
{
public static Claim FindClaim(this IPrincipal user, string claimType)
{
if (user == null) throw new ArgumentNullException(nameof(user));
if (string.IsNullOrEmpty(claimType)) throw new ArgumentNullException(nameof(claimType));
var claimsPrincipal = user as ClaimsPrincipal;
return claimsPrincipal?.FindFirst(claimType);
}
public static string GetEmail(this IPrincipal user)
{
if (user == null) throw new ArgumentNullException(nameof(user));
return FindClaim(user, ClaimTypes.Email)?.Value;
}
public static string GetSurname(this IPrincipal user)
{
if (user == null) throw new ArgumentNullException(nameof(user));
return FindClaim(user, ClaimTypes.Surname)?.Value;
}
public static int? GetUserId(this IPrincipal user)
{
if (user == null) throw new ArgumentNullException(nameof(user));
string value = FindClaim(user, ClaimTypes.Sid)?.Value;
if (string.IsNullOrEmpty(value)) return default(int?);
int result;
return int.TryParse(value, out result) ? result : default(int?);
}
}
这篇关于Mvc访问索赔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!