LESSON 13 OF 16

13. Connecting the Web Application to the REST API

Send HTTP requests from an ASP.NET Core web application, use typed and named HttpClient instances, process DTOs, and display API results in Razor views.

75 dk 81

Introduction

In the previous lessons, we created REST API endpoints, implemented CRUD operations, handled HTTP status codes, and defined data transfer objects. This lesson moves to the other side of the architecture: connecting an ASP.NET Core MVC web application to the API. The web application will not connect directly to SQL Server. Instead, it will retrieve product data through the REST API.

In this design, the web layer is responsible for the user interface and user interaction. The API receives HTTP requests, delegates work to the business layer, and returns DTOs. Data access remains inside the lower layers. This prevents the user interface from becoming directly coupled to the database.

Lesson goal: Send HTTP requests from a .NET web application to the API; use typed or named HttpClient instances, process DTOs, and display API results in the user interface.

Request Flow and Responsibilities

When a user opens the products page, the following flow takes place:

  1. The browser sends a request such as /Products to the web application.
  2. ProductsController calls an application service or API client.
  3. The client sends a GET /api/products request through a configured HttpClient.
  4. The API retrieves products through the business and data layers and returns JSON.
  5. The web application deserializes the JSON into ProductDto objects.
  6. The controller passes the DTO collection to a Razor View.
  7. The view renders the products as an HTML table or another user interface component.

The controller should not contain every detail of the HTTP call. A more maintainable design keeps API communication in a separate client class. ASP.NET Core MVC controllers can receive dependencies through constructor injection, so the client can be registered in the dependency injection container.

Defining the Shared DTO

The JSON returned by the API must match the DTO expected by the web application. You can place the contract in a shared project or define an equivalent DTO in the web project. The web application should consume an API contract rather than directly using a database entity.

public sealed class ProductDto
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public decimal Price { get; set; }
    public string? CategoryName { get; set; }
    public bool IsActive { get; set; }
}

public sealed class ProductListResponse
{
    public IReadOnlyList<ProductDto> Items { get; set; } = [];
    public int TotalCount { get; set; }
}

If the API returns an array directly, use List<ProductDto> instead of ProductListResponse. The important point is that the client model must reflect the actual API response. Mismatched property names or types can result in missing or default values after deserialization.

Using a Named HttpClient

Named clients are useful when an application communicates with several APIs or needs multiple HTTP configurations. The client name identifies settings such as the base address, default headers, and timeout.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllersWithViews();

builder.Services.AddHttpClient("CatalogApi", client =>
{
    client.BaseAddress = new Uri(
        builder.Configuration["ApiSettings:BaseUrl"]!);
    client.Timeout = TimeSpan.FromSeconds(10);
});

var app = builder.Build();

Keep the API address in configuration instead of hard-coding it:

{
  "ApiSettings": {
    "BaseUrl": "https://localhost:7001/"
  }
}

A service can request the named client from IHttpClientFactory:

public sealed class CatalogApiService
{
    private readonly IHttpClientFactory _clientFactory;

    public CatalogApiService(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    public async Task<IReadOnlyList<ProductDto>> GetProductsAsync(
        CancellationToken cancellationToken = default)
    {
        var client = _clientFactory.CreateClient("CatalogApi");
        var response = await client.GetAsync(
            "api/products", cancellationToken);

        response.EnsureSuccessStatusCode();

        var products = await response.Content
            .ReadFromJsonAsync<List<ProductDto>>(cancellationToken);

        return products ?? [];
    }
}

Register the service with dependency injection:

builder.Services.AddScoped<CatalogApiService>();

EnsureSuccessStatusCode throws when the response is unsuccessful. Production applications should log the failure, return a safe user-facing message, and decide whether a retry or fallback is appropriate.

A More Focused Design with a Typed HttpClient

A typed client places the configuration and operations for one API in a dedicated class. The controller does not need to know endpoint paths or JSON serialization details. It also reduces string-based client-name dependencies and provides better IntelliSense support.

public sealed class CatalogApiClient
{
    private readonly HttpClient _httpClient;

    public CatalogApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<IReadOnlyList<ProductDto>> GetProductsAsync(
        CancellationToken cancellationToken = default)
    {
        using var response = await _httpClient.GetAsync(
            "api/products", cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            return [];
        }

        var products = await response.Content
            .ReadFromJsonAsync<List<ProductDto>>(cancellationToken);

        return products ?? [];
    }
}

Register the typed client in Program.cs:

builder.Services.AddHttpClient<CatalogApiClient>(client =>
{
    client.BaseAddress = new Uri(
        builder.Configuration["ApiSettings:BaseUrl"]!);
    client.Timeout = TimeSpan.FromSeconds(10);
});

The typed client constructor must accept an HttpClient. The AddHttpClient<CatalogApiClient> call connects the class to the HTTP client factory. Do not register the same typed client again as a plain transient service, because that can replace the factory-managed registration.

Calling the Client from a Controller

The MVC controller should focus on the UI request and response:

public sealed class ProductsController : Controller
{
    private readonly CatalogApiClient _apiClient;

    public ProductsController(CatalogApiClient apiClient)
    {
        _apiClient = apiClient;
    }

    public async Task<IActionResult> Index(
        CancellationToken cancellationToken)
    {
        var products = await _apiClient
            .GetProductsAsync(cancellationToken);

        return View(products);
    }
}

The controller does not execute SQL and does not construct the full API URL. It passes the DTO collection returned by the API client to the view. This separation makes the controller easier to test and maintain.

Displaying DTOs in a Razor View

Create Views/Products/Index.cshtml and declare a strongly typed model:

@model IReadOnlyList<ProductDto>

<h2>Products</h2>

@if (!Model.Any())
{
    <p>No products were found.</p>
}
else
{
    <table>
        <thead>
            <tr>
                <th>Product</th>
                <th>Category</th>
                <th>Price</th>
                <th>Status</th>
            </tr>
        </thead>
        <tbody>
        @foreach (var product in Model)
        {
            <tr>
                <td>@product.Name</td>
                <td>@(product.CategoryName ?? "-")</td>
                <td>@product.Price.ToString("C2")</td>
                <td>@(product.IsActive ? "Active" : "Inactive")</td>
            </tr>
        }
        </tbody>
    </table>
}

Razor HTML-encodes displayed text by default. Avoid rendering API-provided product names as raw HTML. Use Html.Raw only when the content is trusted and is intentionally stored as HTML.

Handling HTTP Results and Failures

An API request can fail because the API is unavailable, the address is wrong, the network is slow, or the API returns 404, 401, or 500. Instead of exposing exception details in the UI, return a controlled result that the controller can convert into a user-friendly view model.

public sealed class ProductPageViewModel
{
    public IReadOnlyList<ProductDto> Products { get; init; } = [];
    public string? ErrorMessage { get; init; }
}

The client can log failures and return a safe result:

try
{
    using var response = await _httpClient.GetAsync(
        "api/products", cancellationToken);

    if (!response.IsSuccessStatusCode)
    {
        _logger.LogWarning(
            "Products API returned status code {StatusCode}",
            response.StatusCode);
        return new ProductResult([], "Products could not be loaded.");
    }

    var data = await response.Content
        .ReadFromJsonAsync<List<ProductDto>>(cancellationToken);

    return new ProductResult(data ?? [], null);
}
catch (HttpRequestException exception)
{
    _logger.LogError(exception, "Products API request failed");
    return new ProductResult([], "The API connection could not be established.");
}

ProductResult is an application-specific result type. Its purpose is to keep technical details in logs while presenting a safe message to the user. Use the supplied CancellationToken and avoid treating a deliberately cancelled request as an unexpected application error.

Sending Filters in the Query String

If the API supports filtering or pagination, the web application can send query-string values:

public async Task<IReadOnlyList<ProductDto>> SearchAsync(
    string? search, CancellationToken cancellationToken = default)
{
    var query = string.IsNullOrWhiteSpace(search)
        ? string.Empty
        : $"?search={Uri.EscapeDataString(search)}";

    return await _httpClient.GetFromJsonAsync<List<ProductDto>>(
        $"api/products{query}", cancellationToken) ?? [];
}

Encode user-provided values before adding them to a URL. For more complex filters, use a reliable query-string construction approach instead of concatenating many values manually.

Common Mistakes

  • Incorrect BaseAddress: The API and web application may use different HTTPS ports. Verify the API address in Swagger or the local launch configuration.
  • Incorrect relative path: Make sure the base address and endpoint path combine correctly. Use paths such as api/products.
  • Incorrect response model: If the API returns a wrapper object, do not deserialize it directly into a list.
  • Too much controller logic: Keep JSON parsing, header configuration, and HTTP policy decisions out of the controller.
  • Manually creating HttpClient repeatedly: Prefer IHttpClientFactory-based named or typed clients.
  • Ignoring unsuccessful responses: Test 4xx, 5xx, timeout, empty response, and API-unavailable scenarios.
  • Leaking secrets: API keys and service credentials must not be placed in Razor markup or sent to the browser.

Practice Exercise

  1. Add ProductDto to the web project or reference the shared contract project.
  2. Create the ApiSettings:BaseUrl configuration value.
  3. Implement CatalogApiClient and register it with AddHttpClient.
  4. Call GET /api/products from the typed client.
  5. Pass the DTO collection from ProductsController.Index to the view.
  6. Display the product name, category, price, and active status in a Razor table.
  7. Stop the API and verify that the web application displays a controlled error message.

Conclusion

This lesson established real HTTP communication between the web application and the REST API. Named clients provide flexibility when several configurations are required. Typed clients organize the calls for a particular API in one class and are often easier to use in business applications. DTOs ensure that the web layer consumes an explicit API contract without exposing database entities or SQL Server details.

The same structure can now be extended beyond listing data. In the next stages, use the client to submit create, update, and delete requests driven by user interaction. Preserve the separation between the controller, API client, API layer, and data layer to keep the solution maintainable and testable.

Official resources: IHttpClientFactory, ASP.NET Core HTTP requests, and MVC Views.

Sources