DEV Community

Alexandru Bucur
Alexandru Bucur

Posted on

How to get the user id after registering an user in ASP .NET Core Identity

Getting back to work on my side project I got into finishing the user registration trough the API. Following the JSON API spec, it requires returning a 201 created and the resource id when creating a database entry.

For somebody used with ASP this might seem trivial but it's not that obvious when creating a new user.

Let's take a simple example:

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    // do stuff here
}
Enter fullscreen mode Exit fullscreen mode

Usually you would think that result would somehow contain the user's id but that's not the case.
However, if your operation succeeded, the user variable will contain the newly created database properties.

So you can do something like:

return StatusCode(StatusCodes.Status201Created, new {
    data = new { id = user.Id }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
pbouillon profile image
Pierre Bouillon

Hey, I was exactly looking for this, thanks for sharing ! 😄

Collapse
 
salimalitarikz profile image
salimalitarikz

I am quite new to this thing. I am sure of this is what I need. Maybe this is a very basic question but how can I get and use data.