在ASP.NET MVC中获取经过身份验证的身份用户数据

问题描述

我已经创建了一个ASP.NET身份实体框架,并在ASP.NET身份-MVC中添加了用于注册登录功能的客户字段

identityModel.cs

  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;
            }
    
            //add custom fields
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public bool IsAdministrator { get; set; }
    
        }

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

        public DbSet<Property> Property { get; set; }

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

在另一个名为Property的类中(通过登录和身份验证之后)

我想调用AspNetUsers表中的一个字段(当前已登录)。我想检查IsAdministrator字段及其值,并根据该值对要查看的内容做一些条件。

这是我所做的,但没有成功

 public class PropertyController : Controller
    {
        private ApplicationDbContext db = new ApplicationDbContext();
        

        // GET: Property
        [Authorize]
        public async Task<ActionResult> Index()
        {

            var user = System.Web.HttpContext.Current.User.Identity.GetUserId();
            bool admin = db.Users.SingleOrDefault(y => y.Id.Equals("user")).IsAdministrator;
            //return View(await db.Property.ToListAsync());
            if (admin == true){
                return View(await db.Property.Where(x => x.PropertyID == 1).ToListAsync()); }
            else  {
                return View(await db.Property.ToListAsync());}
           
        }

我能够提取当前登录用户的UserID,但是我想要用户的另一个字段或信息,即IsAdmin字段,该字段为1或0。

我该如何实现?

这不起作用

 bool admin = db.Users.SingleOrDefault(y => y.Id.Equals("user")).IsAdministrator;

错误

enter image description here

解决方法

表达式SingleOrDefault(y => y.Id.Equals("user"))没有任何意义。它将使用Id = "user"搜索数据库的用户,却一无所获。这就是为什么它返回null导致NullReferenceException的原因。

尝试使用以下代码段

...
var userId = System.Web.HttpContext.Current.User.Identity.GetUserName();
var user = UserManager.FindByNameAsync(userId);
var isAdmin = user.IsAdministrator;
...

获取用户