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

时间:2016-05-02 13:29:25

标签: asp.net-core-mvc asp.net-identity-3

我已经在寻找Identity 3.0的答案,并且发现很少有关于获得具有int id的单个用户。

我有一个asp.net-core mvc6项目,我在其中使用字符串id转换所有用户和角色以获得整数ID。

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

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

在我的服务中,我想让用户与整数id相关联...&#34; 1&#34;。

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

问题是,这需要一个&#34;字符串&#34; id不是&#34; int&#34;标识。

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

2 个答案:

答案 0 :(得分:9)

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

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

...使用ConfigureServices TypeConverterpublic 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); } 注册时,您已internally convert it back to the key type配置身份:

<?php
    $fullUrl = "https://www.{$myVariable}.test.com"; // Repeat for every variable
    $locationHref = "window.location.href='{$fullUrl};'";
?>

<td>
    <input type="submit" onClick="<?=$locationHref; ?>" value="Click!" />
</td>

答案 1 :(得分:1)

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

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

var user = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == id);
相关问题