Skip to content

BaseController

Base controller with Result pattern helpers.

Attributes

  • [ApiController] - Automatic model validation
  • [Produces("application/json")] - JSON responses

Methods

MethodReturnDescription
ToActionResult(Result)IActionResult200 OK or 400 Bad Request
ToActionResult<T>(Result<T>)IActionResult200 with data or 400
ToCreatedResult<T>(Result<T>, string, object)IActionResult201 Created
ToCreatedResult<T>(Result<T>, string)IActionResult201 with URI
NotFoundResult(string)IActionResult404 Not Found
ForbiddenResult(string?)IActionResult403 Forbidden
ConflictResult(string)IActionResult409 Conflict

Usage

csharp
[Route("api/[controller]")]
public class ProductsController : BaseController
{
    private readonly IMediator _mediator;

    [HttpPost]
    public async Task&lt;IActionResult&gt; Create(CreateProductCommand cmd, CancellationToken ct)
    {
        var result = await _mediator.Send(cmd, ct);
        return ToCreatedResult(result, nameof(GetById), new { id = result.Data });
    }

    [HttpGet("{id:guid}")]
    public async Task&lt;IActionResult&gt; GetById(Guid id, CancellationToken ct)
    {
        var result = await _mediator.Send(new GetProductQuery(id), ct);
        if (result is null) return NotFoundResult("Product not found");
        return Ok(result);
    }
}

Released under the MIT License.