7.8: Setting Main Photo in the API

We have a button to set a user's main photo - let's get that working next.

Adding SetMainPhotoForUser() Service Method

First, in our IPhotoService.cs file, add two method signatures:

Task<Photo> GetMainPhotoForUser(int userId);
Task<bool> SetMainPhotoForUser(int userId, PhotoForReturn photo);

Next, we'll implement these methods in the PhotoService.cs class:

public async Task<Photo> GetMainPhotoForUser(int userId)
{
    return await _context.Photos.Where(u => u.UserId == userId).FirstOrDefaultAsync(p => p.IsMain);
}

public async Task<bool> SetMainPhotoForUser(int userId, PhotoForReturn photo)
{
    var currentMainPhoto = await GetMainPhotoForUser(userId);

    if (currentMainPhoto != null)
        currentMainPhoto.IsMain = false;

    _context.Photos.FirstOrDefault(p => p.Id == photo.Id).IsMain = true;

    return await SaveAll();
}

GetMainPhotoForUser() returns the photo the given user has set to main.

SetMainPhotoForUser() calls the above method to get the current main photo, sets it to false, and sets the photo from the parameter to main.

Adding SetMainPhoto() Method to the PhotosController

[HttpPost("{id}/setMain")]
public async Task<IActionResult> SetMainPhoto(int userId, int id)
{
    if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
        return Unauthorized();

    var photoFromRepo = await _photoService.GetPhoto(id);

    if (photoFromRepo == null)
        return NotFound();

    if (photoFromRepo.IsMain)
        return BadRequest("This is already the main photo");

    if (await _photoService.SetMainPhotoForUser(userId, photoFromRepo))
        return NoContent();

    return BadRequest("Could not set photo to main");
}

Test in Postman

Get a token for a user you know has multiple photos from previous testing for the /api/auth/login endpoint.

Next, send a GET request to /api/users/{id} to see their photos and which on is set to main. Make note of one of the non-main photo's id.

Finally, we can send a POST request to /api/users/{userId}/photos/{photoId}/setMain/:

You should get a 204 No Content response:

Resend the GET request to /api/users/{id} to verify that the IsMain properties on the photos have been swapped:

Last updated