[英]Can't retrieve UserId from Microsoft.AspNet.Identity
我創建了一個新類,我想管理一些事情,其中之一是獲取用戶ID Microsoft.AspNet.Identity
。 我收到此錯誤消息
CS0103當前上下文中不存在名稱“用戶”
這是我的代碼:
using Microsoft.AspNet.Identity;
public string UserId
{
get
{
return User.Identity.GetUserId();
}
}
我期待intellisense能夠使用Microsoft.AspNet.Identity
GetUserId
方法,但出現以下錯誤。
我在做錯什么,為什么它不能從Microsoft.AspNet.Identity
提取UserId
。
您應該像這樣使用HttpContext.Current.User
:
public string UserId
{
get { return HttpContext.Current.User.Identity.GetUserId(); }
}
因為基於MSDN :
如果要使用ASP.NET代碼隱藏模塊中IPrincipal的成員,則必須在模塊中包括對System.Web命名空間的引用,以及對當前活動的請求/響應上下文和類的完全限定引用。在System.Web中要使用。 例如,在代碼隱藏頁面中,您必須指定標准名稱HttpContext.Current.User.Identity.Name。
另一個要注意的是,您還可以使用C#6+的新功能,稱為表達式主體屬性,如下所示:
public string UserId => HttpContext.Current.User.Identity.GetUserId();
您需要對當前活動請求/響應上下文的引用,才能訪問User屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.