Search code examples
c#entity-frameworkasp.net-core-mvcasp.net-identity

ASP.NET CORE 5.0 Identity Display current logged in user


I am try to display in Index Page which user submite ticket. In my Model I add property

 public int? UserId { get; set; }

 public virtual ApplicationUser ApplicationUser { get; set; }

And In controller I have something like

 [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Upsert(TicketVM ticketVM)
        {
            if (ModelState.IsValid)
            {
                if (ticketVM.Ticket.Id == 0)
                {
                    ticketVM.Ticket.Status = TicketStatus.Otvoren.ToString();
                    _unitOfwork.Ticket.Add(ticketVM.Ticket);
                }
                else
                {
                    _unitOfwork.Ticket.Update(ticketVM.Ticket);
                }
                _unitOfwork.Save();
                return RedirectToAction(nameof(Index));
            }
            return View(ticketVM);
        }

SO far I try to add something like this

var userEmail = User.FindFirstValue(ClaimTypes.Email);
ticketVM.Ticket.ApplicationUser.Name = userEmail;

Here is problem that I get error message

Object reference not set to an instance of an object.

So my question is, How can I assigne in IndexPage after user is logged in and submit ticket I need to display his/her username or email address.

ApplicationUser.cs

 public class ApplicationUser : IdentityUser
    {
        
        [Required]
        [Display(Name = "Ime")]
        public string Name { get; set; }

        [Required]
        [Display(Name = "Adresa")]
        public string StreetAddress { get; set; }

        [Required]
        [Display(Name = "Grad")]
        public string City { get; set; }

        [Required]
        [Display(Name = "Postanski broj")]
        public string PostalCode { get; set; }

        public int? ClientId { get; set; }
        [ForeignKey("ClientId")]
        public Client Client { get; set; }

        [NotMapped]
        public string Role { get; set; }
    }

Solution

  • That error indicates that ApplicationUser is NULL. So when you try to access the Name property, it throws that error. You could just do something like this assuming its an existing user:

    ticketVM.Ticket.ApplicationUser = _dbContext.Users.FirstOrDefault(u => u.Email == userEmail);

    You could also use the UserManager built in class which has a FindByEmail() method as well. But the point is, FIRST grab the ApplicationUser from the DB using the userEmail. If its a new user, then you need to create a new ApplicationUser in order to access the Name property.