如何访问已登录用户的属性?

时间:2017-10-05 15:37:50

标签: c# asp.net asp.net-mvc asp.net-core-mvc-2.0

我正在学习Asp.net Core MVC 2.0,无法弄清楚如何访问已登录用户的属性。

为了便于说明,让我们使用Visual Studio社区生成的Asp.net Core MVC 2.0的默认模板,并选择Individual User Account

该模板为我们提供了一个从ApplicationUser继承的空IdentityUser。同样,为简单起见,我只向Point添加了一个属性ApplicationUser,如下所示。

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

Point将跟踪登录用户访问“/ Home / Index”的次数。为简单起见,这是一个微不足道的场景。

问题

现在,我不知道如何访问该属性Point并在每次访问/Home/Index时将其递增一个。

我尝试通过Point访问该媒体资源User.Identity,如下所示,但失败了。

enter image description here

你能告诉我正确的方法吗?

1 个答案:

答案 0 :(得分:2)

试试这个,并参考你的问题,你也可以更新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);
}