# 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:

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

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

```csharp
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

```csharp
[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.

![UserCheck](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8tzgEezX8uYIqF2l%2Fusercheck.png?generation=1524162341109226\&alt=media)

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

You should get a `204 No Content` response:

![SetMain204](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8u0KOkUG2BcFbch-%2Fsetmain204.png?generation=1524162341050213\&alt=media)

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

![SwappedMain](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8u1ZY8RW3EEOD-Ak%2FswappedMainPhoto.png?generation=1524162341074776\&alt=media)
