Identity 3.0 当 id 为 "int" 时通过 id 获取用户

Identity 3.0 Getting a user by id when the id is "int"

我已经四处寻找有关 Identity 3.0 的答案,但几乎没有找到有关获取具有 int id 的单个用户的信息。

我有一个 asp.net-core mvc6 项目,我在其中将所有具有字符串 ID 的用户和角色转换为具有整数 ID。

很好。这样可行。我有一个 UserAdminController,其中包括一个更新或编辑操作,它传递一个 "int?" 作为 id。

public async Task<IActionResult> Edit(int? id)

在我的服务中,我想获取与整数 id 关联的用户...“1”。

我想使用 UserManger.FindByIdAsync(id) 获取具有该 ID 的用户。

问题是,这需要 "string" id 而不是 "int" id。

使用 UserManger(如果可以的话)我如何 return 使用整数而不是字符串 ID 的用户?必须有一种优雅的方式来 return 用户?

Aliz 走在正确的轨道上,但他建议的方法在 Identity 3.0 中不存在。

然而,这确实可以使用作为基础的 Aliz 选项编号 1..

var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == id);

只需将您的用户标识符作为字符串传输...

var user = _userManager.FindByIdAsync("1");

... 身份将 internally convert it back to the key type 您在 ConfigureServices 中使用 TypeConverter:

注册时配置的
public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken))
{
    cancellationToken.ThrowIfCancellationRequested();
    ThrowIfDisposed();
    var id = ConvertIdFromString(userId);
    return Users.FirstOrDefaultAsync(u => u.Id.Equals(id), cancellationToken);
}


public virtual TKey ConvertIdFromString(string id)
{
    if (id == null)
    {
        return default(TKey);
    }
    return (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString(id);
}