Search code examples
c#asp.netasp.net-mvcasp.net-core-mvc-2.0

How to access the properties of a logged-in user?


I am learning Asp.net Core MVC 2.0 and cannot figure out how to access the properties of a logged-in user.

For illustration purpose, let's use the default template of Asp.net Core MVC 2.0 generated by Visual Studio Community with Individual User Account selected.

The template provides us with an empty ApplicationUser that inherits from IdentityUser. Again, for simplicity, I added just one property Point to the ApplicationUser as follows.

public class ApplicationUser : IdentityUser
{
    public int Point { get; set; }
}

The Point will keep track the number of times a logged-in user visits "/Home/Index". It is a trivial scenario for simplicity.

Question

Now, I have no idea how to access the property Point and increment it by one every time he/she visits /Home/Index.

I attempted to access the property Point via User.Identity is shown as follows, but failed.

enter image description here

Could you tell me the correct way?


Solution

  • Try this, and refer to your question, you can also update Point:

    private readonly UserManager<ApplicationUser> _userManager;
    
    public HomeController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }
    
    public async Task<IActionResult> GetCurrentUserAsync()
    {
       var currentUser = await _userManager.GetUserAsync(User);
       if (currentUser is null)
       {
           //handle this as you wish
       }
       currentUser.Point++;
       await _usermanager.UpdateAsync(currentUser);
    }