Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 805
FrankO Avatar asked Jan 26 '14 22:01

FrankO


People also ask

How do you create an identity user?

To create Users in ASP.NET Core Identity you will need to create a Model Class. So create a class called User. cs inside the Models folders. Users are managed through the UserManager<T> class, where T is the class chosen to represent users in the database.

What is identity user in asp net?

ASP.NET Identity is the membership system for authentication and authorization of the users by building an ASP.NET application. ASP.NET Identity is the membership system for authentication and authorization of the users by building an ASP.NET application.


1 Answers

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; } 
like image 87
Jelle Oosterbosch Avatar answered Sep 18 '22 20:09

Jelle Oosterbosch