如果您使用的是 ASP.NET WebForms 模板附带的默认成员资格,您应该执行以下操作来检索用户:
if (this.User != null && this.User.Identity.IsAuthenticated)
{
var userName = HttpContext.Current.User.Identity.Name;
}
您所说的新模型是ClaimsPrincipal
. 独特的区别是这个基于声明的安全,它与旧版本完全兼容,但更强大。
编辑:
要将用户添加到某些Role
程序中,您应该这样做,传递用户名和角色名:
if (this.User != null && this.User.Identity.IsAuthenticated)
{
var userName = HttpContext.Current.User.Identity.Name;
System.Web.Security.Roles.AddUserToRole(userName, "Role Name");
}
使用新的基于声明的安全性
if (this.User != null && this.User.Identity.IsAuthenticated)
{
var userName = HttpContext.Current.User.Identity.Name;
ClaimsPrincipal cp = (ClaimsPrincipal)HttpContext.Current.User;
GenericIdentity genericIdentity;
ClaimsIdentity claimsIdentity;
Claim claim;
genericIdentity = new GenericIdentity(userName, "Custom Claims Principal");
claimsIdentity = new ClaimsIdentity(genericIdentity);
claim = new Claim(ClaimTypes.Role, "Role Name");
claimsIdentity.AddClaim(claim);
cp.AddIdentity(claimsIdentity);
}