无法从 Microsoft.AspNet.Identity 检索 UserId

Can't retrieve UserId from Microsoft.AspNet.Identity

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

CS0103 The name 'User' does not exist in the current context

这是我的代码:

using Microsoft.AspNet.Identity;

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

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

我做错了什么,为什么它不能从 Microsoft.AspNet.Identity 中获取 UserId

您需要引用当前活动的 request/response 上下文才能访问用户 属性。

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

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

因为基于MSDN:

if you want to use the members of IPrincipal from an ASP.NET code-behind module, you must include a reference to the System.Web namespace in the module and a fully qualified reference to both the currently active request/response context and the class in System.Web that you want to use. For example, in a code-behind page you must specify the fully qualified name HttpContext.Current.User.Identity.Name.

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

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