【问题标题】:Can't retrieve UserId from Microsoft.AspNet.Identity无法从 Microsoft.AspNet.Identity 检索 UserId
【发布时间】:2018-03-12 01:56:18
【问题描述】:

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

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

这是我的代码:

using Microsoft.AspNet.Identity;

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

我原以为智能感知会采用 Microsoft.AspNet.Identity GetUserId 方法,但我收到以下错误。

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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我用过这个 HttpContext.Current.User.Identity.GetUserId();它有效,您认为这是正确的使用方法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-19
      • 2019-01-23
      相关资源
      最近更新 更多