10.2: Add Messages Controller

In your .API/Controllers folder, add a new controller called MessagesController.cs.

We'll start by adding an Authorize attribute, adding our ActionFilter to log user activity, and adding our Route attribute. We'll also inject our MessageService and UserService into the controller:

[Authorize]
[ServiceFilter(typeof(LogUserActivity))]
[Route("api/users/{userId}/[controller]")]
public class MessagesController : Controller
{
    private readonly IMessageService _messageService;
    private readonly IUserService _userService;

    public MessagesController(IMessageService messageService, IUserService userService)
    {
        _messageService = messageService;
        _userService = userService;
    }
}

Add Get Message Method

Next, we'll add a GetMessage() method. We'll give it a Name attribute, because we'll use it in our Create route (remember CreatedAtRoute()?).

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

    var message = await _messageService.GetMessage(id);

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

    return Ok(message);
}

Add Create Message Method

Next, we'll add a CreateMessage() method below:

[HttpPost]
public async Task<IActionResult> CreateMessage(int userId, [FromBody] MessageForCreation messageForCreation)
{
    if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
        return Unauthorized();

    messageForCreation.SenderId = userId;

    var messageToReturn = await _messageService.CreateMessage(messageForCreation);

    if (messageToReturn != null)
        return CreatedAtRoute("GetMessage", new { id = messageToReturn.Id }, messageToReturn);

    throw new Exception("Creating the message failed on save.");
}

Testing in Postman

Get a fresh token from the /api/auth/login endpoint.

Send a POST request to http://localhost:5000/api/users/{senderId}/messages. Supply the user Id of the user you have the token for in the endpoint.

We'll also include a body with the recipientId and the message content. Here's an example:

{
    "recipientId": "2104",
    "content": "Test message from Anita to Flores"
}

You should get a 201 Created response with the senderId, recipientId, dateSent, and content in the response:

SendMessagePostman

Last updated