C# / .NET Compendium PLEN
.NET / C# / Web API, Blazor

Returning a result from Web API - ActionResult<T>

The basic pattern

[HttpGet("{id}")]
public async Task<ActionResult<OrderDto>> GetOrder(int id)
{
    var order = await _orderService.GetOrderAsync(id);
    if (order == null)
        return NotFound(); // 404, with no value

    return Ok(order); // 200 + a value in the body
}

ActionResult<T> lets you return either a value of type T (implicitly converted to 200 OK), or any other IActionResult (an error, another status).

Typical helper methods (ControllerBase)

return Ok(order);                          // 200
return Ok();                                // 200 bez body
return NotFound();                          // 404
return BadRequest("Invalid data");    // 400
return BadRequest(ModelState);              // 400 with validation errors
return Conflict();                          // 409
return Unauthorized();                      // 401
return Forbid();                            // 403
return NoContent();                         // 204 - typical for DELETE/PUT with no returned content
return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order); // 201 + Location header

Error handling - two approaches

1. Returning an error code directly (as above) - good for typical, expected situations (404, 400).

2. Exceptions + a global middleware (for unexpected errors)

// Middleware for global exception handling
app.UseExceptionHandler(errorApp =>
{
    errorApp.Run(async context =>
    {
        context.Response.StatusCode = 500;
        var error = context.Features.Get<IExceptionHandlerFeature>();
        await context.Response.WriteAsJsonAsync(new { message = "A server error occurred" });
    });
});

The Result/OneOf pattern (an alternative to exceptions, common with CQRS) - instead of throwing an exception, you return an object representing success/failure:

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);
}

This avoids the cost of exceptions for expected business errors (e.g. "the order doesn't exist" is not an exceptional situation, just a normal result of a query).

ProblemDetails - the standard error format (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 = "Order not found",
            Status = 404,
            Detail = $"The order with id {id} does not exist"
        });
    return Ok(order);
}

[ApiController] automatically returns ProblemDetails for validation errors (400) - this is a standardised JSON format for API errors that clients (WPF, Blazor) can parse uniformly.

Buy me a coffee