Skip to content

Instantly share code, notes, and snippets.

@sskset
Created September 3, 2019 13:03
Show Gist options
  • Save sskset/d269ec2a5da03cce0498572dc5c54918 to your computer and use it in GitHub Desktop.
Save sskset/d269ec2a5da03cce0498572dc5c54918 to your computer and use it in GitHub Desktop.
FluentValidationController
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
using Users.API.Application.Commands;
using Users.API.Application.Queries;
namespace Users.API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly IMediator _mediator;
private readonly ILogger<UsersController> _logger;
public UsersController(IMediator mediator, ILogger<UsersController> logger)
{
_mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// Create a user
/// </summary>
/// <param name="command">User info</param>
/// <returns>User created</returns>
[HttpPost]
public async Task<IActionResult> CreateAsync(CreateUserCommand payload)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var userCreated = await _mediator.Send(command);
if (userCreated == null)
{
throw new Exception("Error in creating user");
}
return CreatedAtAction(nameof(GetByIdAsync), new { id = userCreated.Id }, userCreated);
}
catch (FluentValidation.ValidationException vex)
{
return BadRequest(new { vex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message, command);
return StatusCode(StatusCodes.Status500InternalServerError, new
{
message = "Error in creating user."
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment