Subclassing IdentityUser ASP.NET

1.1k views Asked by At

I have a Web API and I want my AutoHubUser to be used instead of the default one (IdentityUser). But I keep getting internal server error when I try to save it. What needs to be changed?

public class AutoHubUser : IdentityUser
{
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Date)]
    [Display(Name = "Birth Date")]
    public DateTime BirthDate { get; set; }

    [Required]
    public Gender Gender { get; set; }

    public virtual ICollection<Auto> Autos { get; set; }
    public virtual ICollection<UserMilestone> UserMilestones { get; set; }
    public virtual ICollection<Friendship> Friendships { get; set; }
}

The account controller

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        IdentityUser user = new AutoHubUser
        {
            UserName = model.UserName,
            Email = model.Email,
            BirthDate = model.BirthDate,
            Gender = model.Gender
        };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);
        //IdentityResult result = await new UserManager<AutoHubUser>().CreateAsync(user, model.Password);
        IHttpActionResult errorResult = GetErrorResult(result);

        if (errorResult != null)
        {
            return errorResult;
        }

        return Ok();
    }

I also modified the RegisterBindingModel

public class RegisterBindingModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }


    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Date)]
    public DateTime BirthDate { get; set; }

    [Required]
    public Gender Gender { get; set; }
}

What else needs to be modified? It must be in the UserManager's CreateAsync method. But I haven't been able to find an example online. Thanks!

0

There are 0 answers