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

FrankO picture FrankO · Jan 26, 2014 · Viewed 49.1k times · Source

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.

Answer

Jelle Oosterbosch picture Jelle Oosterbosch · Jan 27, 2014

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;
}