如何在 _Layout.cshtml 中检索标识声明值



我在谷歌上搜索了很长时间,但仍然无法得到正确的答案。我正在使用标识声明进行用户身份验证,并且需要_Layout.cshtml页面中的一些声明值。但是,我可以检索自定义标识声明值,但不能检索内置值。

在这里,我设置了我的身份:

var ident = new ClaimsIdentity(
new[] { 
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, user.LoginId),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,user.UserName),
new Claim(ClaimTypes.Sid,user.UserId.ToString()),
new Claim("OperationType", user.OperationType.ToString()),
new Claim("ImageLink", user.ImageLink.ToString())
},
DefaultAuthenticationTypes.ApplicationCookie);
var claimsPrincipal = new ClaimsPrincipal(ident);
// Set current principal
Thread.CurrentPrincipal = claimsPrincipal;

和我的布局页面代码:

@using System.Security.Claims;
...........
@{  
string userDesignation = ((ClaimsIdentity)User.Identity).FindFirst("OperationType").Value; ;
string userImage = ((ClaimsIdentity)User.Identity).FindFirst("ImageLink").Value; ;
}

我可以检索我的自定义声明(图像链接,操作类型(值,但无法检索具有相同模式的(名称,Sid(。我发现的一些答案是关于扩展方法的。这是检索值的唯一方法还是有其他方法? 提前致谢

请在布局页面顶部使用线程命名空间

@using System.Threading;

并按如下方式访问您的索赔类型

@{  
string userDesignation = ((ClaimsIdentity)User.Identity).FindFirst("OperationType").Value;
string userImage = ((ClaimsIdentity)User.Identity).FindFirst("ImageLink").Value;

var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
// Get the claims values
var id= identity.Claims.Where(c => c.Type == ClaimTypes.Sid)
.Select(c => c.Value).SingleOrDefault();
var s = id;
//so on.......
}

但@Erik飞利浦是对的。您应该将这些逻辑用作部分逻辑。

您可以使用从布局中调用的方法创建布局控制器。RenderPartial(( (来自下面的评论@Erik飞利浦(。

TextInfo myTI = new CultureInfo("en-US", false).TextInfo;
var claimsIdentity = HttpContext.Current.User.Identity as System.Security.Claims.ClaimsIdentity;
var displayNameClaim = (claimsIdentity == null) ? null : claimsIdentity.Claims.SingleOrDefault(x => x.Type == ApplicationUser.DisplayNameClaimType);
var nameToDisplay = (displayNameClaim == null) ? HttpContext.Current.User.Identity.Name : displayNameClaim.Value;
var nameToDisplayTitle = myTI.ToTitleCase(nameToDisplay);

在视图中,名称值被注入到<span class="NameDisplay"></span>中。

$(".NameDisplay").html(@Html.Raw(""" + nameToDisplayTitle + """));

IdentityModels.cs中,我定义了以下字段:

public class ApplicationUser : IdentityUser
{
public const string DisplayNameClaimType = "FirstName";
[Display(Name = "First Name")]
public string FirstName { get; set; }
//etc.
}

并定义此声明:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim(DisplayNameClaimType, FirstName));
return userIdentity;
}

最新更新