BaseController
Base controller with Result pattern helpers.
Attributes
- [ApiController] - Automatic model validation
- [Produces("application/json")] - JSON responses
Methods
| Method | Return | Description |
|---|---|---|
| ToActionResult(Result) | IActionResult | 200 OK or 400 Bad Request |
| ToActionResult<T>(Result<T>) | IActionResult | 200 with data or 400 |
| ToCreatedResult<T>(Result<T>, string, object) | IActionResult | 201 Created |
| ToCreatedResult<T>(Result<T>, string) | IActionResult | 201 with URI |
| NotFoundResult(string) | IActionResult | 404 Not Found |
| ForbiddenResult(string?) | IActionResult | 403 Forbidden |
| ConflictResult(string) | IActionResult | 409 Conflict |
Usage
csharp
[Route("api/[controller]")]
public class ProductsController : BaseController
{
private readonly IMediator _mediator;
[HttpPost]
public async Task<IActionResult> 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<IActionResult> 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);
}
}