You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core中是否存在UserManager<TUser, TKey>?如何无需转字符串调用FindByIdAsync

在.NET Core Identity中配置int主键并直接使用int调用FindByIdAsync
  1. 定义自定义角色(可选,若需角色功能)
    如果项目需要角色管理,创建继承自IdentityRole<int>的自定义角色类:
public class ApplicationRole : IdentityRole<int>
{
    // 可按需添加自定义角色属性
}
  1. 配置数据库上下文
    让DbContext继承自IdentityDbContext<ApplicationUser, ApplicationRole, int>,确保数据库表使用int类型主键:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}
  1. 注册Identity服务
    在Program.cs(或Startup.cs)中注册Identity服务时,指定自定义用户和角色类型,确保所有Identity组件适配int主键:
// Program.cs示例配置
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>(options =>
{
    // 可配置Identity相关选项,例如登录验证要求
    options.SignIn.RequireConfirmedAccount = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

若无需角色功能,可简化为:

builder.Services.AddIdentity<ApplicationUser, IdentityRole<int>>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
  1. 添加UserManager扩展方法
    由于.NET Core Identity默认的FindByIdAsync仅接受string参数,添加扩展方法直接支持int类型的用户ID:
public static class UserManagerExtensions
{
    public static async Task<ApplicationUser?> FindByIdAsync(this UserManager<ApplicationUser> userManager, int userId)
    {
        return await userManager.FindByIdAsync(userId.ToString());
    }
}

完成以上配置后,你就可以直接调用await _userManager.FindByIdAsync(1);,无需手动将int转换为字符串。

内容的提问来源于stack exchange,提问作者jstuardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:55:16