ASP.NET Core 8 Web API endpoint does not contain my custom fields

690 Views Asked by At

I created an entity ApplicationUser and successfully extended it to IdentityUser and migrations created it in the database.

But when I go to the register endpoint, it does not show my custom fields to be registered:

enter image description here

enter image description here

Entity 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>();
2

There are 2 best solutions below

1
Jalpa Panchal On

There can be possible reason if the API endpoint that handles registration is not configured to accept the additional fields of your ApplicationUser. could you try this below code:

public class RegisterDto
{
    public string Email { get; set; }
    public string Password { get; set; }

    // Custom fields
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int FavoriteTeam { get; set; }
    public string PhotoPath { get; set; }
}

Update the registration endpoint

public async Task<IActionResult> Register(RegisterDto model)
{
    var user = new ApplicationUser
    {
        UserName = model.Email,
        Email = model.Email,
        FirstName = model.FirstName,
        LastName = model.LastName,
        FavoriteTeam = model.FavoriteTeam,
        PhotoPath = model.PhotoPath
    };

    // other registration process
}
0
Abdullah Etizaz On

Here is one way to write a custom identity register endpoint. This endpoint takes a RegisterDTO and maps it to a User object.

[HttpPost("CustomRegister")]
public async Task<Results<Ok, ValidationProblem>> PostNew (RegisterDTO registration,  [FromServices] IServiceProvider sp) {

    var userManager = sp.GetRequiredService<UserManager<User>>();

    if (!userManager.SupportsUserEmail)
    {
        throw new NotSupportedException($"User store with email support required.");
    }

    var userStore = sp.GetRequiredService<IUserStore<User>>();
    var emailStore = (IUserEmailStore<User>)userStore;
    var email = registration.Email;

       if (string.IsNullOrEmpty(email) || !_emailAddressAttribute.IsValid(email))
          {
                    return CreateValidationProblem(IdentityResult.Failed(userManager.ErrorDescriber.InvalidEmail(email)));
          }

     var user = new User();
     user.Contact = new Contact
         {
                    FirstName = registration.Firstname,
                    MiddleName = registration.Middlename,
                    LastName = registration.Lastname,
                    PhoneNumbers = new List<PhoneNumber> { new PhoneNumber
                {
                    Number = registration.Phonenumber
                } },
                    Selfie= registration.Profilephoto,
                    IDImage = registration.Idimage

            };

     await userStore.SetUserNameAsync(user, registration.Username, CancellationToken.None);
     await emailStore.SetEmailAsync(user, email, CancellationToken.None);
     var result = await userManager.CreateAsync(user, registration.Password);

       if (!result.Succeeded)
            {
                return CreateValidationProblem(result);
            }

 //   await SendConfirmationEmailAsync(user, userManager, context, email);
      return TypedResults.Ok();
    }

I wrote this using code from microsoft identityApiEndpointRouteBuilderExtensions so it should be work flawlessly with other identity features. You can find the actual code on https://github.com/dotnet/aspnetcore/blob/main/src/Identity/Core/src/IdentityApiEndpointRouteBuilderExtensions.cs.