4.7: Adding Users Controller

Add Users Controller

In the Controller folder in your .API project - add a new class named UsersController.cs that derives from the Controller class.

We'll also go ahead and lock this Controller down the with [Authorize] attribute and specify the route this controller will use with the [Route] attribute.

Add a constructor and inject the IUserService.

[Authorize]
[Route("api/[controller]")]
public class UsersController : Controller
{
    private readonly IUserService _userService;

    public UsersController(IUserService userService)
    {
        _userService = userService;
    }
//  ...

Add Controller Methods

Next, we're going to add the methods the controller will use to handle HTTP requests for getting all users and getting a specific user:

[HttpGet]
public async Task<IActionResult> GetUsers()
{
    var users = await _userService.GetUsers();

    return Ok(users);
}

[HttpGet("{id}")]
public async Task<IActionResult> GetUser(int id)
{
    var user = await _userService.GetUser(id);

    return Ok(user);
}

Testing the UsersController

Ensure your .API project is running and open Postman.

First we'll verify that our UsersController is locked down by trying a GET request to http://localhost:5000/api/users. It should return a 401 Unauthorized response.

"Login" via Postman with one of your newly created users. Check your database to find a username - all passwords should be "password" if you followed the seeding tutorial. Send a POST request to the /api/auth/login endpoint with your credentials. You should get a 200 OK response and a tokenString

Copy the tokenString from the last response and paste it in the header as we've done before.

Try a GET request to /api/users again. This time it should work!

Now, we'll try to get an individual user. You should have an Id of a user from your last response. Append it to the end of the url

localhost:5000/api/users/{id}

In my case, I'm using 2103 because I forgot to comment out the seeder.SeedUsers(); method in the Startup class previously...

Wrap-up

Good job!

That was a lot of work, but we have our API working for Users and Photos the way we want.

Next, we can work on consuming the API in our Angular project and our application will really start to take shape!

Last updated