无法从Microsoft.AspNet.Identity检索UserId

时间:2018-03-12 01:56:18

标签: c# asp.net-mvc asp.net-identity-3

我创建了一个新类,我想管理一些事情,其中​​一个是获取用户ID Microsoft.AspNet.Identity。我收到此错误消息

  

CS0103当前上下文中不存在“用户”名称

这是我的代码:

using Microsoft.AspNet.Identity;

public string UserId
{
    get
    {
        return User.Identity.GetUserId();
    }
}

enter image description here

我希望intellisense能够选择Microsoft.AspNet.Identity GetUserId方法,但我收到以下错误。

我做错了什么,为什么不能从UserId拿起Microsoft.AspNet.Identity

2 个答案:

答案 0 :(得分:4)

你应该像这样使用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。

另外请注意,您还可以使用名为expression-bodied property的C#6+新功能:

public string UserId => HttpContext.Current.User.Identity.GetUserId();

答案 1 :(得分:1)

您需要对当前活动请求/响应上下文的引用才能访问User属性。