ASP.NET Identity and Web API - Problem to register new user

Asked

Viewed 482 times

5

I have a Web API project and I’m using Identity to manage user accounts, my controller is like this:

public async Task<IHttpActionResult> Register([FromBody]RegisterDto model)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    try
    {
        var registerDomain = Mapper.Map<RegisterDto, Customer>(model);
        registerDomain.UserName = registerDomain.Email;
        _customerService.Insert(registerDomain);
        IdentityResult result = await UserManager.CreateAsync(registerDomain, model.Password);

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

        var code = await UserManager.GenerateEmailConfirmationTokenAsync(registerDomain.Id); 
        var callbackUrl = Url.Link("DefaultApi", new { controller = "Account", action = "ConfirmEmail", userId = registerDomain.Id, code = code });
        await UserManager.SendEmailAsync(registerDomain.Id, "Confirmação de conta", "Porfavor confirme a sua conta clicando nesse link: <a href=\"" + callbackUrl + "\">link</a>");
    }
    catch (Exception ex)
    {
        return BadRequest();
    }

    return Ok();
}

But the result of UserManager.CreateAsync is making the following mistake: Name cannot be null or empty.

Name is a property of Customer (Customer inherits from IdentityUser) and the string is being passed on correctly, including in RegisterDto the property is required, if it was null or empty it did not pass the ModelState.

I’ve searched the net and there are people with the same problem, but the solutions are not working, someone can give a tip?

The code of RegisterDto

public class RegisterDto
{
    public string Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public int Cpf { get; set; }

    [Required]
    public string Email { get; set; }

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

    [Required]
    [DataType(DataType.Password)]
    [Compare("Password", ErrorMessage = "A senha e a confirmação da senha não são iguais.")]
    public string ConfirmPassword { get; set; }
}
  • I forgot to mention, I believe it has nothing to do directly with the property Name of Customer, I say this because in the answers I found on the net the custom class of Identityuser had no property called Name, really I’m lost here. :(

  • Can you please edit your question and enter the code for RegisterDto?

  • @I added the code to the RegisterDto.

1 answer

2


This problem is not very easy to solve because the error message does not help much. Actually the source of the problem is here:

registerDomain.UserName = registerDomain.Email;

By default, the user entity validator does not accept characters like the @ and the . in UserName. This is why it is necessary to adjust the validator before accepting special characters for the user name:

UserManager.UserValidator = new UserValidator<TUser>(UserManager) { 
                                  AllowOnlyAlphanumericUserNames = false }
  • Had already made this configuration, and also had already tested put the login without special characters, the error persists.

  • @Well, I wouldn’t use the Automapper if I were you. Even if it generates a correct object, I would do the manual process first to make sure it’s working.

  • I tested without using Automapper, changed to receive the class Customer so I don’t have to do the mapping. Now gave an Exception: The Entity type Customer is not part of the model for the Current context, already a better msg... :) I’ll test more to know where the problem is.

  • Okay, let me know. I update the response in the course.

  • actually the autoMapper was not mapping correctly, the property Email was null in mapping, so it gave the message Name cannot be null or empty and found that this Name property refers to the Username of IdentityUser. Only today I had time to analyze Exception. Because of this error I realized that my class Customer (who inherits from IdentityUser) when the table is created in the database only has the properties of the IdentityUser, the custom properties I’ve made don’t appear, so you’re giving Exception.

  • @rhgm In short, does the answer serve? Or do I need to modify it?

  • 1

    It does, now the problem is different, so it’s another question. Thank you!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.