Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserManager.AddPasswordAsync() returns "Name cannot be null or empty"

I work with MVC5 and ASP.NET identity framework.

I've extended the account manage-functionality which is scaffolded by VS2013.

If my user has registered with an external login provider and wants to add a local password I get and error when I call "AddPasswordAsync()": "Name cannot be null or empty"

I have looked in my db and confirmed that the username is not null.

What does this error mean?

My ApplicationUser looks like this:

public class Person : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Sex Sex { get; set; }

    [Display(Name = "Birth date")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime Birthdate { get; set; }
    public string EMail { get; set; }
    public int PostalCode { get; set; }

    public Collection<Race> Races { get; set; }
    public Collection<Participation> Participations { get; set; }

    public Person()
    {
        if (string.IsNullOrEmpty(UserName))
        {
            UserName = EMail;
        }
        Participations = new Collection<Participation>();
        Races = new Collection<Race>();
        Birthdate = DateTime.Now;
    }
}

Best regards Frederik

like image 249
Frederik Avatar asked Mar 20 '23 11:03

Frederik


2 Answers

I finally solved it after a lot of tries. The error message is wrong, it comes from the database and means that username field is null but the database requires it.

Make sure you send the db the user name like that for example:

 var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Hometown = model.Hometown };

And make sure that the database is up to date before that by running update-database.

like image 147
Ronen Festinger Avatar answered May 03 '23 08:05

Ronen Festinger


Well, I was hoping your ApplicationUser would elicit more clues as to what the problem is, but I'm not seeing anything that stands outs. So, here's what advice I can give. It's not asking about UserName; it's explicitly saying "Name is required". AddPasswordAsync is merely saving the user object to the database, so you need to look deeper and make sure that the entire object is clean, i.e. no validation errors. Something, somewhere is failing validation, so my first step would be to run a project or even solution-wide search for "Name". Unfortunately, you're likely to get a ton of false positives for something as general as that, but when you finally find a property or properties with that name, that's most likely your culprit.

like image 34
Chris Pratt Avatar answered May 03 '23 09:05

Chris Pratt