无法从 Microsoft.AspNet.Identity 检索 UserId

The*_*lin 1 c# asp.net-mvc asp.net-identity-3

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

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

这是我的代码:

using Microsoft.AspNet.Identity;

public string UserId
{
    get
    {
        return User.Identity.GetUserId();
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我期待智能感知选择该Microsoft.AspNet.Identity GetUserId方法,但我收到以下错误。

我做错了什么,为什么它不能UserIdMicrosoft.AspNet.Identity.

Sal*_*ari 5

你应该这样使用HttpContext.Current.User

public string UserId
{
    get { return HttpContext.Current.User.Identity.GetUserId(); }
}
Run Code Online (Sandbox Code Playgroud)

因为基于MSDN

如果要使用 ASP.NET 代码隐藏模块中的 IPrincipal 成员,则必须在模块中包含对 System.Web 命名空间的引用以及对当前活动请求/响应上下文和类的完全限定引用在您要使用的 System.Web 中。例如,在代码隐藏页面中,您必须指定完全限定名称 HttpContext.Current.User.Identity.Name。

作为另一个注意事项,您还可以使用 C# 6+ 新功能,称为expression-bodied 属性,如下所示:

public string UserId => HttpContext.Current.User.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)