【问题标题】:Get current user id in ASP.NET Identity 2.0在 ASP.NET Identity 2.0 中获取当前用户 ID
【发布时间】:2014-05-02 16:46:45
【问题描述】:

我刚刚切换到使用新的 2.0 版身份框架。在 1.0 中,我可以使用 manager.FindByIdAsync(User.Identity.GetUserId()) 获取用户对象。 GetUserId() 方法似乎在 2.0 中不存在。

现在我能想到的就是使用manager.FindByEmailAsync(User.Identity.Name),它引用了用户表中的用户名字段。在我的应用程序中,这设置为与电子邮件字段相同。

当有人需要更新他们的电子邮件时,我可以看到这会导致问题。有没有办法根据 Identity 2.0 框架中不变的值(例如 id 字段)获取当前登录的用户对象?

【问题讨论】:

  • 您是如何获得 UserId 的,请告诉我,我遇到了同样的问题。

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


【解决方案1】:

GetUserId()IIdentity 的扩展方法,位于Microsoft.AspNet.Identity.IdentityExtensions 中。确保您已使用 using Microsoft.AspNet.Identity; 添加命名空间。

【讨论】:

  • 这似乎不适用于 Identity 2。请提供任何建议
  • 应该还在。我现在在我的 Identity 2 项目中使用 GetUserId()。
  • 在 Identity 3.0 中,这似乎已移至 System.Security.Principal 命名空间。
  • 有什么方法可以获取当前用户角色?我什么时候应该设置角色?注意:我正在使用自定义存储提供程序..
【解决方案2】:

为了获取Asp.net Identity 2.0中的CurrentUserId,首先导入Microsoft.AspNet.Identity

C#:

using Microsoft.AspNet.Identity;

VB.NET:

Imports Microsoft.AspNet.Identity


然后随时随地拨打User.Identity.GetUserId()

strCurrentUserId = User.Identity.GetUserId()

此方法返回当前用户 ID 作为数据库中用户 ID 定义的数据类型(默认为 String)。

【讨论】:

  • 你能告诉我在哪里可以找到 Microsoft.AspNet.Identity 命名空间对应的 DLL 吗?
【解决方案3】:

万一你和我一样,并且用户实体的 Id 字段是 Int 或字符串以外的其他东西,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

会成功的

【讨论】:

    【解决方案4】:

    我有同样的问题。我目前正在使用 Asp.net Core 2.2。我用下面的代码解决了这个问题。

    using Microsoft.AspNetCore.Identity;
    var user = await _userManager.FindByEmailAsync(User.Identity.Name);
    

    我希望这对某人有用。

    【讨论】:

    • 你救了我的命
    猜你喜欢
    • 2016-12-09
    • 2014-05-27
    • 2012-10-20
    • 2023-03-16
    • 2019-03-24
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多