Home Register A New User In Asp.Net Core Web Api
Post
Cancel

Register A New User In Asp.Net Core Web Api

Alt text

Here is where we get into the meat and potatoes a bit more. Let’s start adding some endpoints and get our Auth and Auth underway.

Start by adding a new, empty Api Controller to your Controllers folder. I have named mine “AccountController”.

Controller and a Register Method

Here is my basic Account Controller with a Register method added in:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
namespace ApothecaricApi.Controllers
{
  [Route("api/[controller]")]
  public class AccountController : Controller
  {
    private readonly UserManager<ApothecaricUser> userManager;

    public AccountController(UserManager<ApothecaricUser> userManager)
    {
      this.userManager = userManager;
    }

  [HttpPost]
  [Route("Register")]
  public async Task<IActionResult> TempRegister([FromBody] RegisterViewModel model)
  {
    var user = new ApothecaricUser
    {
      UserName = model.Email,
      Email = model.Email
    };

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

    if (result.Succeeded)
    return Created("", result);

    return BadRequest();
    }
  }
}

If we look back, on line 6 we need to create a member variable to get at Core’s built-in UserManager in order for us to interact with the Asp.Net Identity database. In line 8-11 we need to create a constructor that will take in our UserManager object. The UserManager object needs our custom user class injected in to know how to deal with the new fields that we have added to the AspNetUsers table.

For now, I have a very crude “Register” method added so that we can create a new user and use that new account for our logins. I have created a RegisterViewModel class and then mapped that our ApothercaricUser in lines 17-21. In a later post, we can look at using AutoMapper to do this work for us. On line 23 we call the UserManager’s CreateAsync method and pass in our ApothecaricUser object and the password we will use for this account. If all goes well, we return a “Created” 201 response. If all goes to hell, we will send back a 400 error.

Disclaimer ;)

As I stated, this initial controller endpoint is crude for the moment. We will also look at a MUCH better way to handle return values and codes and also do some validation to our incoming arguments. Also, I would rather have my admin users create accounts than having that free-for-all “register” method that we all see for signing up for free accounts.

Register Middleware

As it stands now, if we try to run this and post to it using Postman, the call will not work. We need to add some configuration for this to work. We need to go back to our Startup.cs class and look at the ConfigureServices method and tell our application to add the Identity middleware to our flow. We also need to tell the Identity framework what data store to use.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<ApothecaricDbContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("AuthenticationConnection"),
      b => b.MigrationsAssembly("ApothecaricApi")));

  services.AddIdentity<ApothecaricUser, IdentityRole>(cfg =>
  {
    cfg.User.RequireUniqueEmail = true;
  })
  .AddEntityFrameworkStores<ApothecaricDbContext>();

  services.AddMvc();
}

Here on line 8 we tell the app to register the Core’s Identity middleware. On the registration, we need to inject our ApothercaricUser again along with the IdentityRole object. The IdentityRole object is required but we will not be using it so don’t let that confuse you. In the config section on line 10 I just tell the Identity framework that I want user’s emails to be unique in my system. The Identity framework will go a check for me and alert the app if any duplicates are encountered and then the app can deal with appropriately.

Last, on line 12, we tell the Identity Framework what data store we will be using. In our case it’s the ApothecaricDbContext that we created in an earlier post.

Try It Out

Now, go over to Postman and register a new user. If all goes well, you should get the “Created” 201 result.

Alt text

What A Yahoo!

Alt text

Next up, let’s put in the “login” method. Here we will really just check the user credentials and issue a Jwt token if all goes well.

Hope to see you then!

This post is licensed under CC BY 4.0 by the author.