2.6: Add Register Functionality

Now we will give a user the ability to register via our API.

Add Register() Method

This will be a POST method to the api/Auth/Register endpoint.

In AuthController.cs, add the following method:

[HttpPost("Register")]
public async Task<IActionResult> Register([FromBody] UserForRegister userForRegister)
{
    // TODO: validate the request

    userForRegister.Username = userForRegister.Username.ToLower();

    if (await _authService.UserExists(userForRegister.Username))
        return BadRequest("Username is already taken");

    var userToCreate = new User
    {
        Username = userForRegister.Username
    };

    var createUser = await _authService.Register(userToCreate, userForRegister.Password);

    return StatusCode(201);     //  we'll improve this later
}

Right now, our register method will return a StatusCode 201 - which is what we want. However, ideally it would also return the path to the created user using the CreatedAtRoute() method. Right now, we don't have this endpoint and we'll update this method later.

Testing Register Endpoint in Postman

Now, let's test our register method.

Open Postman and send a POST request to http://localhost:5000/api/auth/register with a username and password in the body in JSON format:

Resend the request - and see if we get an error message when we try to create an existing user:

Open up SQL Server Management Studio and browse to your EFConnect database.

In your users table, verify that you have the created user

Last updated