Add UpdateUser() method and endpoint to the UsersController
In the UsersController.cs file, add a new HttpPut method for UpdateUser():
Testing
In Postman, send a Put request to /api/users/{id} - entering an appropriate id from your database (in the example I'm using 2103 - yours will likely be different). Don't forget to provide a fresh Bearer token from the user you are updating in the header.
You should get a 204 No Content response:
UpdateUser
You can send a get request to the same endpoint to check that it has changed:
CheckUpdateUserPostman
The changes should also be reflected in the Angular application:
CheckUpdateUserAngular
We've tested the "happy path", let's test a couple of scenarios when something goes wrong.
First, let's try to update a user that doesn't exist. Send repeat the previous request, but change the id to something you know doesn't exist in your database.
You should get a 404 Not Found response with a body of "User could not be found."
User404d
Next, let's try to update a that is different from the one we have a token for. Change the id in the endpoint to another user's id:
You should get a 401 Unauthorized response.
User401d
Persisting Changes Made on the Client
In user.service.ts, add an updateUser() method:
In member-edit.component.ts, update the updateUser() method to use the UserService instead of console.logging:
Test it out in the browser. You should be able to update profile fields, save them, and see that the changes have persisted.
[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, [FromBody]UserForUpdate userForUpdate)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
var userFromRepo = await _userService.GetUser(id);
if (userFromRepo == null)
return NotFound($"User could not be found.");
if (currentUserId != userFromRepo.Id)
return Unauthorized();
if (await _userService.UpdateUser(id, userForUpdate))
return NoContent();
throw new Exception($"Updating user failed on save.");
}