2014-03-25 43 views
64

我剛剛切換到使用身份框架的新2.0版本。在1.0中,我可以通過使用manager.FindByIdAsync(User.Identity.GetUserId())來獲取用戶對象。在2.0中似乎不存在GetUserId()方法。在ASP.NET身份2.0中獲取當前用戶ID

現在我所能想到的就是使用manager.FindByEmailAsync(User.Identity.Name),它引用users表中的用戶名字段。在我的應用程序中,它設置爲與電子郵件字段相同。

當有人需要更新他們的電子郵件時,我可以看到這導致問題。有沒有辦法根據身份2.0框架中的不變值(如id字段)獲取當前登錄的用戶對象?

+0

你是如何獲取用戶標識,請你讓我知道,我遇到了同樣的問題。 –

回答

80

GetUserId()IIdentity的擴展方法,它在Microsoft.AspNet.Identity.IdentityExtensions。確保你已經添加了名字空間using Microsoft.AspNet.Identity;

+0

另請參閱:http://stackoverflow.com/questions/20925822/asp-mvc5-identity-how-to-get-current-applicationuser –

+1

這似乎與身份不起作用2.任何建議請 –

+2

仍然應該在那裏。我現在在我的Identity 2項目中使用GetUserId()。 –

49

爲了得到CurrentUserId在Asp.net身份2.0,在第一次導入Microsoft.AspNet.Identity

C#:

using Microsoft.AspNet.Identity; 

VB.NET:

Imports Microsoft.AspNet.Identity 


然後致電User.Identity.GetUserId()無處不在,你想:

strCurrentUserId = User.Identity.GetUserId() 

此方法返回當前用戶ID爲數據庫中的用戶ID定義的數據類型(默認爲String)。

+0

您能告訴我哪裏可以我發現了Microsoft.AspNet.Identity命名空間的相應DLL。 – Franziee

9

萬一你是和我一樣的用戶實體的ID字段是int或不是一個字符串別的東西等,

using Microsoft.AspNet.Identity; 

int userId = User.Identity.GetUserId<int>(); 

會做的伎倆