【问题标题】:Can not find User.Identity.GetUserId() Method找不到 User.Identity.GetUserId() 方法
【发布时间】:2015-04-07 06:36:03
【问题描述】:

使用 Visual Studio 2013 Express MVC 应用程序并参考 MVC 5.2 Asp.Net.Identity.Core 2.0

在我的应用程序中的任何控制器或其他任何地方,GetUserId() 方法似乎都不存在,我终生无法理解这是怎么回事。我的印象是它是 Asp.Net Identity 2x 中包含的一种方法。我可能在这里遗漏了什么?

【问题讨论】:

  • 你添加命名空间Microsoft.AspNet.Identity了吗?
  • 它在那里......哇......因为我可以访问 User.Identity.Name 和 IsAuthenticated 而不添加该命名空间......我认为它只是可用......谢谢!
  • 是的,这有点棘手,因为 User.Identity 可用。如果您在GetUserId() 上转到(f12),您将看到它位于 IdentityExtensions 的组中。这很简洁,因为它是一个小模板,可以使用 System.Security.Principal 创建您自己的扩展
  • 试试这个answer这解决了我的问题

标签: asp.net-mvc asp.net-mvc-5 asp.net-identity


【解决方案1】:

这是一种扩展方法。引用类顶部的名称空间。

using Microsoft.AspNet.Identity;

【讨论】:

    【解决方案2】:

    自 2015 RC1 起,GetUserId 扩展方法位于 System.Security.Claims 命名空间中。

    【讨论】:

      【解决方案3】:

      您可以通过 ClaimTypes.NameIdentifier 获取 userId

      var userId =  User.FindFirstValue(ClaimTypes.NameIdentifier)
      

      当然要在顶部加上 using。

      using System.Security.Claims;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-07
        • 2020-03-16
        • 2021-05-31
        • 2018-10-28
        • 2011-04-01
        相关资源
        最近更新 更多