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

ASP.NET Core 8 Web API注册端点不显示自定义字段问题

问题:自定义ApplicationUser字段未出现在Identity注册端点参数中

已创建继承自IdentityUser的ApplicationUser实体,完成数据库迁移并生成对应表,但调用注册端点时,自定义字段(如FirstName、LastName等)未出现在请求参数列表中。

相关代码

ApplicationUser实体

public class ApplicationUser : IdentityUser
{
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public int FavoriteTeam { get; set; }
    public string? PhotoPath { get; set; }
    public string? FirstLast { get; set; }
}

DbContext

public class ContextBase : IdentityDbContext<ApplicationUser>
{
    public ContextBase(DbContextOptions<ContextBase> options) : base(options)
    {
    }
}

Program配置

builder.Services.AddIdentityApiEndpoints<ApplicationUser>()
    .AddEntityFrameworkStores<ContextBase>();
     
-----

app.MapIdentityApi<ApplicationUser>();

解决方案

默认的Identity API端点使用内置模型,仅包含IdentityUser的标准字段,不会自动适配自定义扩展字段,需要手动扩展注册逻辑:

  1. 创建自定义注册请求DTO
    定义包含所有需要字段的请求模型,确保覆盖自定义属性:
public class RegisterRequest
{
    [Required]
    public string Email { get; set; } = string.Empty;
    
    [Required]
    public string Password { get; set; } = string.Empty;
    
    public string? FirstName { get; set; }
    public string? LastName { get; set; }
    public int FavoriteTeam { get; set; }
    public string? PhotoPath { get; set; }
}
  1. 替换默认注册端点
    移除app.MapIdentityApi<ApplicationUser>();,手动映射注册端点并处理自定义字段赋值:
app.MapPost("/register", async (RegisterRequest request, UserManager<ApplicationUser> userManager, ILogger<Program> logger) =>
{
    var user = new ApplicationUser
    {
        UserName = request.Email,
        Email = request.Email,
        FirstName = request.FirstName,
        LastName = request.LastName,
        FavoriteTeam = request.FavoriteTeam,
        PhotoPath = request.PhotoPath,
        // 按需计算派生字段FirstLast
        FirstLast = $"{request.FirstName} {request.LastName}".Trim()
    };

    var result = await userManager.CreateAsync(user, request.Password);

    if (!result.Succeeded)
    {
        foreach (var error in result.Errors)
        {
            logger.LogError("注册错误: {Code} - {Description}", error.Code, error.Description);
        }
        return Results.BadRequest(result.Errors);
    }

    // 可选:为用户添加默认角色
    // await userManager.AddToRoleAsync(user, "普通用户");

    return Results.Ok("注册成功");
})
.WithName("Register")
.WithOpenApi();
  1. 说明
    AddIdentityApiEndpoints和MapIdentityApi提供的是极简默认实现,仅支持标准身份字段。自定义字段需要通过手动定义请求模型、映射端点的方式,将请求参数赋值给ApplicationUser实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 02:22:40