【问题标题】:How to get and set custom user information in mvc 5 Identity?如何在 mvc 5 Identity 中获取和设置自定义用户信息?
【发布时间】:2016-10-26 12:08:25
【问题描述】:

我当前的代码如下。

public class ApplicationUser : IdentityUser
{
    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
        return userIdentity;
    }

}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

我想在 ApplicationUser 类中添加更多属性,以便这些字段在视图中可用,例如

@User.Identity.FullName

我的登录操作位于here

【问题讨论】:

标签: c# asp.net asp.net-mvc-5 asp.net-identity


【解决方案1】:

为了能够得到它的方式:

1 - 您需要为该用户创建声明

HttpContext.Current.GetOwinContext().GetUserManager<UserManager>().AddClaimsAsync(UserId, new Claim("FullName", "The value for the full name"));

2 - 为用户添加声明后,您可以使用它。我制作了这个扩展类,以便能够在视图中获取声明值。

public static class IdentityExtensions
{
    public static string FullName(this IIdentity identity)
    {
        return ((ClaimsIdentity)identity).FindFirst("FullName")?.Value;
    }
}

有了这个你可以像@User.Identity.FullName()一样称呼它

【讨论】:

  • 我已经尝试过这个,但我得到了一个错误。空引用错误。
  • 试一试什么对象为空?
猜你喜欢
  • 1970-01-01
  • 2013-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-01
  • 2020-12-07
  • 2018-07-23
  • 1970-01-01
相关资源
最近更新 更多