我正在尝试使用新的 Visual Studio 2013 Preview for Web 在 Web 表单项目中获取当前用户。我可以使用 Page.User 获取用户名,但尝试获取用户 ID 是我卡住的地方。它正在使用他们提出的这个新的身份模型。

这就是我所拥有的:

//Gets the correct username
string uname = User.Identity.Name;
//Returns a null object
Microsoft.AspNet.Identity.IUser user = IdentityConfig.Users.Find(uname);
//What I hope to call to add a user to a role
IdentityConfig.Roles.AddUserToRole("NPO", user.Id);

最佳答案

如果您使用 ASP.NET WebForms 模板附带的默认成员身份,您应该执行以下操作来检索用户:

if (this.User != null && this.User.Identity.IsAuthenticated)
{
  var userName = HttpContext.Current.User.Identity.Name;
}

您正在谈论的新模型是 ClaimsPrincipal 。唯一的区别是这个 Claims Based Secury ,它与旧版本完全兼容,但功能更强大。

编辑:

要将用户以编程方式添加到某些 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);
}

关于asp.net - 获取当前用户 ASP.NET Visual Studio 2013 Preview ClaimsPrincipal,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18724443/

10-17 01:51