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

Using ActionResult on the client side (WPF/Blazor consuming Web API)

The key distinction to start with

ActionResult<T> is a type returned by the controller on the server side - the client (WPF, Blazor WASM, a console) never sees it directly. The client gets only a raw HTTP response - a status code (200, 404, 400...) and possibly JSON in the body. The client's job is to interpret that HTTP response and translate it back into something meaningful in your code (success + data, or an error + a message).

The basic approach - HttpClient + checking StatusCode

public class OrderApiClient : IOrderApiClient
{
    private readonly HttpClient _httpClient;
    public OrderApiClient(HttpClient httpClient) => _httpClient = httpClient;

    public async Task<OrderDto> GetOrderAsync(int id)
    {
        var response = await _httpClient.GetAsync($"api/orders/{id}");

        if (response.StatusCode == HttpStatusCode.NotFound)
            return null; // the server returned NotFound() -> here we interpret that as "no such order"

        response.EnsureSuccessStatusCode(); // throws an exception for other errors (4xx/5xx)

        return await response.Content.ReadFromJsonAsync<OrderDto>(); // deserializacja JSON -> OrderDto
    }
}

The Result<T> pattern on the client side - mirroring what the server returns

public class ApiResult<T>
{
    public bool IsSuccess { get; private set; }
    public T Value { get; private set; }
    public string ErrorMessage { get; private set; }
    public HttpStatusCode StatusCode { get; private set; }

    public static ApiResult<T> Success(T value, HttpStatusCode statusCode)
        => new() { IsSuccess = true, Value = value, StatusCode = statusCode };

    public static ApiResult<T> Failure(string error, HttpStatusCode statusCode)
        => new() { IsSuccess = false, ErrorMessage = error, StatusCode = statusCode };
}
public class OrderApiClient : IOrderApiClient
{
    private readonly HttpClient _httpClient;

    public async Task<ApiResult<OrderDto>> GetOrderAsync(int id)
    {
        var response = await _httpClient.GetAsync($"api/orders/{id}");

        if (response.IsSuccessStatusCode)
        {
            var order = await response.Content.ReadFromJsonAsync<OrderDto>();
            return ApiResult<OrderDto>.Success(order, response.StatusCode);
        }

        // Try to read ProblemDetails, if the server returned it
        var problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
        var errorMessage = problem?.Detail ?? "An unexpected error occurred";

        return ApiResult<OrderDto>.Failure(errorMessage, response.StatusCode);
    }
}

Usage in a WPF ViewModel

public class OrderDetailsViewModel : ViewModelBase
{
    private readonly IOrderApiClient _apiClient;

    private OrderDto _order;
    public OrderDto Order
    {
        get => _order;
        set => SetProperty(ref _order, value);
    }

    private string _errorMessage;
    public string ErrorMessage
    {
        get => _errorMessage;
        set => SetProperty(ref _errorMessage, value);
    }

    private bool _isLoading;
    public bool IsLoading
    {
        get => _isLoading;
        set => SetProperty(ref _isLoading, value);
    }

    public ICommand LoadOrderCommand { get; }

    public OrderDetailsViewModel(IOrderApiClient apiClient)
    {
        _apiClient = apiClient;
        LoadOrderCommand = new AsyncRelayCommand(LoadOrderAsync);
    }

    private async Task LoadOrderAsync()
    {
        IsLoading = true;
        ErrorMessage = null;

        var result = await _apiClient.GetOrderAsync(orderId: 5);

        if (result.IsSuccess)
        {
            Order = result.Value;
        }
        else if (result.StatusCode == HttpStatusCode.NotFound)
        {
            ErrorMessage = "The order does not exist.";
        }
        else
        {
            ErrorMessage = result.ErrorMessage; // you show the error in the UI, binding refreshes automatically
        }

        IsLoading = false;
    }
}
<StackPanel>
    <TextBlock Text="{Binding ErrorMessage}" Foreground="Red"
               Visibility="{Binding ErrorMessage, Converter={StaticResource StringToVisibilityConverter}}" />
    <ProgressBar IsIndeterminate="{Binding IsLoading}" />
    <TextBlock Text="{Binding Order.CustomerName}" />
</StackPanel>

Handling write operations (POST) - CreatedAtAction on the client side

Server:

[HttpPost]
public async Task<ActionResult<OrderDto>> CreateOrder(CreateOrderRequest request)
{
    var order = await _orderService.CreateOrderAsync(request);
    return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order); // 201 + Location header
}

Client:

public async Task<ApiResult<OrderDto>> CreateOrderAsync(CreateOrderRequest request)
{
    var response = await _httpClient.PostAsJsonAsync("api/orders", request);

    if (response.StatusCode == HttpStatusCode.Created) // 201
    {
        var order = await response.Content.ReadFromJsonAsync<OrderDto>();
        return ApiResult<OrderDto>.Success(order, response.StatusCode);
    }

    if (response.StatusCode == HttpStatusCode.BadRequest) // 400 - validation errors
    {
        var validationErrors = await response.Content.ReadFromJsonAsync<ValidationProblemDetails>();
        var messages = string.Join(", ", validationErrors.Errors.SelectMany(e => e.Value));
        return ApiResult<OrderDto>.Failure(messages, response.StatusCode);
    }

    return ApiResult<OrderDto>.Failure("Unknown error", response.StatusCode);
}

Blazor - an identical mechanism, a different context

@inject IOrderApiClient ApiClient

<button @onclick="LoadOrder">Load the order</button>
@if (isLoading) { <p>Loading...</p> }
@if (errorMessage != null) { <p class="text-danger">@errorMessage</p> }
@if (order != null) { <p>@order.CustomerName</p> }

@code {
    private OrderDto order;
    private string errorMessage;
    private bool isLoading;

    private async Task LoadOrder()
    {
        isLoading = true;
        var result = await ApiClient.GetOrderAsync(5);

        if (result.IsSuccess) order = result.Value;
        else errorMessage = result.ErrorMessage;

        isLoading = false;
        StateHasChanged(); // a manual refresh, if outside the normal event cycle
    }
}

Handling network exceptions (a separate category from HTTP errors)

This is a different category of problem from "the server returned 404" - here we mean situations where it was not possible at all to reach the server:

public async Task<ApiResult<OrderDto>> GetOrderAsync(int id)
{
    try
    {
        var response = await _httpClient.GetAsync($"api/orders/{id}");
        // ... handling as above
    }
    catch (HttpRequestException ex)
    {
        // No connection, DNS didn't resolve, the server is offline, etc.
        return ApiResult<OrderDto>.Failure("No connection to the server", HttpStatusCode.ServiceUnavailable);
    }
    catch (TaskCanceledException ex) when (ex.InnerException is TimeoutException)
    {
        // Timeout - HttpClient.Timeout was exceeded
        return ApiResult<OrderDto>.Failure("Przekroczono czas oczekiwania", HttpStatusCode.RequestTimeout);
    }
}

It is important that WPF/Blazor never crashes when the internet connection drops - instead it shows a sensible message to the user.

An automatically generated typed client - an alternative (Refit/OpenAPI)

Worth mentioning as a curiosity - instead of writing an OrderApiClient by hand with HttpClient, libraries such as Refit let you define the contract as an interface:

public interface IOrderApi
{
    [Get("/api/orders/{id}")]
    Task<ApiResponse<OrderDto>> GetOrderAsync(int id); // ApiResponse<T> z Refit - opakowuje HttpResponseMessage + dane

    [Post("/api/orders")]
    Task<ApiResponse<OrderDto>> CreateOrderAsync([Body] CreateOrderRequest request);
}

Refit's ApiResponse<T> plays a similar role to my hand-written ApiResult<T> - it wraps both the StatusCode and the deserialised value, so you don't have to write HttpClient.GetAsync + status checking by hand every time.

Summary - the bridge between server and client

The server-side ActionResult<T> (Ok(order), NotFound(), BadRequest(...)) translates solely into an HTTP status code + an optional JSON body - the client has no access to the fact that the server "returned NotFound()", it only sees response.StatusCode == HttpStatusCode.NotFound. That is why it is crucial to design both sides symmetrically: the server consistently returns the appropriate status codes for different situations, and the client (through its own wrapper such as ApiResult<T>, or a library like Refit) consistently interprets them back into something the ViewModel/Blazor component can show the user - an error, no data, or success with a value.

Buy me a coffee