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:
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:
You should get a 201 Created response with the senderId, recipientId, dateSent, and content in the response:

Last updated