How to create a user and get the newly created ID with ASP.NET Identity

54,677

Solution 1

Using the IdentityUser or using a class that inherits from IdentityUser, makes the model having an UserId attribute. Using following code, passing the user to the method, will fill up the Id.

var user = model.GetUser();
var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded)
    result = UserManager.AddToRole(user.Id, "User");

The model.GetUser() returns an object of the ApplicationUser or IdentityUser

public ApplicationUser GetUser()
{
    var user = new ApplicationUser
    {
        UserName = UserName,
        FirstName = FirstName,
        LastName = LastName,
        Email = Email,
        ...
    };

    return user;
}

Solution 2

The accepted answer was not clear to me so I thought I would share this.

If you look at the source for the IdentityUser class you will find the following.

public class IdentityUser : IdentityUser<string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>
{
    /// <summary>
    ///     Constructor which creates a new Guid for the Id
    /// </summary>
    public IdentityUser()
    {
        this.Id = Guid.NewGuid().ToString();
    }
    ... code omitted
}

As you can see, when creating a new IdentityUser instance the constructor generates a new GUID and populates the Id field.

This means if you create a new instance of a derived class such as ApplicationUser a new Id will still automatically be generated for you.

So, after you check that the user has been successfully added you can safely use the Id in the ApplicationUser class for your data association.

Example.

var user = new ApplicationUser
{
    UserName = "franko",
    FirstName = "Frank",
    LastName = "Ouimette",
    Email = "[email protected]"
};

var result = await UserManager.CreateAsync(user, model.Password);

if (result.Succeeded){
    result = UserManager.AddToRole(user.Id, "User");

    // User added successfully, you can safely use the Id now.
    var id = user.Id;

}

Solution 3

What worked for me was something slightly different:

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var user = new ApplicationUser() { Email = "[email protected]", UserName = "[email protected]" };
var result = manager.Create(user, "TestPass44!");

if (result.Succeeded)
{
    string newId = user.Id;
}

Solution 4

Some extension methods have been added to the Identity framework, including this one:

public static string GetUserId(this IIdentity identity);

After performing the sign-in, you should be able to retrieve the ID easily enough:

await SignInAsync(user, isPersistent: false);
var id = this.User.Identity.GetUserId()

Solution 5

This thread is already a few years old, but I encountered this problem and needed to find another solution because I do not use the provided Guids, but a standard integer ID, provided by the database (auto-incremented index).

The problem that I had was that if I created the user with UserManager.CreateAsync, the user object wasn't updated with the ID. I then created a related object for that user, and since the ID wasn't updated, Entity Framework tried to save the user to the database another time which resulted in a primary key violation.

To solve the problem, I needed to read/update the user object like so:

var user = new User
{
    UserName = UserName,
    FirstName = FirstName,
    LastName = LastName,
    Email = Email,
    ...
};

var result = await UserManager.CreateAsync(user, model.Password);

// At this point, the user has been created, but the ID not set

// Read the full user record from the database
user = db.Users.Where(u => u.Email == user.Email).FirstOrDefault();

// At this point, the user has the correct ID set, we are good to go...
Share:
54,677
FrankO
Author by

FrankO

Updated on January 04, 2020

Comments

  • FrankO
    FrankO over 4 years

    I am new to the ASP.NET Identity framework and am trying to do some things that I used to do in the older FormsAuthentication framework.

    What I want to do is allow an administrative user to create a new user using the existing Register view (or similar) from within the app. Once this is complete, I would like to relationally associate that user (possibly using the ID that is generated) to other areas of the system.

    How do I get access to the ID that is generated when calling UserManager.CreateAsync()?

    EDIT: I am wanting existing users with "administrative" roles to create users from within the system in a User Management area. The answers below so far have explained how to get the ID for the "current" user which is not what I am looking for.