Zwracanie rezultatu z Web API - ActionResult<T>
Podstawowy wzorzec
[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> GetOrder(int id)
{
var order = await _orderService.GetOrderAsync(id);
if (order == null)
return NotFound(); // 404, bez wartości
return Ok(order); // 200 + wartość w body
}
ActionResult<T> pozwala zwrócić albo wartość typu T (niejawnie konwertowaną na 200 OK), albo dowolny inny IActionResult (błąd, inny status).
Typowe metody pomocnicze (ControllerBase)
return Ok(order); // 200
return Ok(); // 200 bez body
return NotFound(); // 404
return BadRequest("Nieprawidłowe dane"); // 400
return BadRequest(ModelState); // 400 z błędami walidacji
return Conflict(); // 409
return Unauthorized(); // 401
return Forbid(); // 403
return NoContent(); // 204 - typowe dla DELETE/PUT bez zwracanej treści
return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order); // 201 + Location header
Obsługa błędów - dwa podejścia
1. Zwracanie kodu błędu bezpośrednio (jak wyżej) - dobre dla typowych, oczekiwanych sytuacji (404, 400).
2. Wyjątki + globalny middleware (dla nieoczekiwanych błędów)
// Middleware do globalnej obsługi wyjątków
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
var error = context.Features.Get<IExceptionHandlerFeature>();
await context.Response.WriteAsJsonAsync(new { message = "Wystąpił błąd serwera" });
});
});
Wzorzec Result/OneOf (alternatywa dla wyjątków, częsta przy CQRS) - zamiast rzucać wyjątek, zwracasz obiekt reprezentujący sukces/porażkę:
public class Result<T>
{
public bool IsSuccess { get; }
public T Value { get; }
public string Error { get; }
public static Result<T> Success(T value) => new(true, value, null);
public static Result<T> Failure(string error) => new(false, default, error);
}
[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> GetOrder(int id)
{
var result = await _orderService.GetOrderAsync(id);
return result.IsSuccess ? Ok(result.Value) : NotFound(result.Error);
}
To unika kosztu wyjątków dla oczekiwanych błędów biznesowych (np. "zamówienie nie istnieje" to nie jest wyjątkowa sytuacja, tylko normalny wynik zapytania).
ProblemDetails - standardowy format błędów (RFC 7807)
[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> GetOrder(int id)
{
var order = await _orderService.GetOrderAsync(id);
if (order == null)
return NotFound(new ProblemDetails
{
Title = "Zamówienie nie znalezione",
Status = 404,
Detail = $"Zamówienie o id {id} nie istnieje"
});
return Ok(order);
}
[ApiController] automatycznie zwraca ProblemDetails dla błędów walidacji (400) - to jest standaryzowany format JSON dla błędów API, który klienci (WPF, Blazor) mogą jednolicie parsować.