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

5

I have a Web API project and I'm using Identity to manage user accounts, in my controller it looks 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 giving the following error: Name cannot be null or empty .

Name is a property of Customer ( Customer inherits from IdentityUser ) and the string is being passed correctly, including RegisterDto ownership is required, if it were null or empty was not passed in% check%.

I've already researched the net and there are people with the same problem, but the solutions are not working, can anyone give a tip?

The code for ModelState

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; }
}
    
asked by anonymous 19.05.2015 / 22:42

1 answer

2

This problem is not very easy to resolve because the error message does not help much. In fact the source of the problem is here:

registerDomain.UserName = registerDomain.Email;

By default, the validator of the user entity does not accept characters such as @ and . in UserName . This is why you need to first adjust the validator to accept special characters for the user name:

UserManager.UserValidator = new UserValidator<TUser>(UserManager) { 
                                  AllowOnlyAlphanumericUserNames = false }
    
20.05.2015 / 16:43