2017-10-05 64 views
0

我正在學習Asp.net核心MVC 2.0,無法弄清楚如何訪問登錄用戶的屬性。如何訪問登錄用戶的屬性?

爲了便於說明,我們使用由Visual Studio Community生成的默認模板Asp.net Core MVC 2.0,並選擇Individual User Account

該模板爲我們提供了一個從IdentityUser繼承的空的ApplicationUser。同樣,爲了簡單起見,我僅向ApplicationUser添加了一個屬性Point,如下所示。

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

Point將跟蹤次登錄的用戶訪問「/首頁/索引」的數量。這對於簡單來說是一個微不足道的場景。

問題

現在,我不知道如何訪問屬性Point和每一個他/她訪問/Home/Index時間增加了。

我試圖通過User.Identity訪問屬性Point顯示如下,但失敗。

enter image description here

你能告訴我正確的方法是什麼?

+1

你嘗試用(ApplicationUSer)User.Identity鑄造? –

回答

2

試試這個,並參閱你的問題,你也可以更新點:

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); 
} 
+0

對不起。有沒有關於這種技術的文件? –

+0

@ArtificialStupidity肯定,[這裏是](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?tabs=visual-studio%2Caspnetcore2x) –

+0

你通過閱讀該頁面上的評論? –

相關問題