我正在学习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
,如下所示,但失败了。
你能告诉我正确的方法吗?
答案 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);
}