LESSON 16 OF 16

16. End-to-End Project: Administration Panel and REST API

Build a realistic product administration panel by combining SQL Server, 3-tier architecture, a REST API, and a web client.

180 dk 66

Introduction

In this final lesson, we will combine all the building blocks from the course into one realistic application. Our example project is a simple administration panel where authorized users can list products, add new products, update existing products, and remove or deactivate products. The application will use SQL Server as its data store, Entity Framework Core for data access, a service-oriented business layer, an ASP.NET Core REST API, and a web client that communicates with the API.

The goal is not merely to create a few screens or endpoints. The main objective is to complete the entire journey of a user action: a browser request is sent to the web application, the web application calls the REST API, the API applies application rules, the data access layer communicates with SQL Server, and the result travels back through the layers to the user.

A feature is not complete just because a database table or API endpoint exists. The user interface, validation, error handling, data access, and response contract must work together.

Project scope and layer responsibilities

We will use a Product entity. Each product will have a name, description, price, stock quantity, and active status. To keep the example focused, categories, file uploads, and reporting are outside the current scope, but the design can be extended later.

LayerResponsibilityExample components
DomainDefines core entities and shared contracts.Product, constants
Data AccessCommunicates with SQL Server.AppDbContext, repository
BusinessApplies validation and application rules.ProductService
APIExposes HTTP endpoints and external contracts.ProductsController
WebRenders administration pages and calls the API.ProductApiClient, Razor View

The web layer should not connect directly to SQL Server or use the API project's DbContext. Likewise, the API should not expose database implementation details. This separation reduces the impact of changes and keeps each component easier to test and maintain.

Step 1: Define the entity and DTOs

The domain entity represents the object persisted in the database:

public class Product {    public int Id { get; set; }    public string Name { get; set; } = string.Empty;    public string? Description { get; set; }    public decimal Price { get; set; }    public int StockQuantity { get; set; }    public bool IsActive { get; set; }    public DateTime CreatedAtUtc { get; set; } }

Instead of returning the entity directly from the API, use data transfer objects. This prevents database-specific fields from becoming part of the public contract and allows input and output models to evolve independently.

public record ProductListItemDto(    int Id,    string Name,    decimal Price,    int StockQuantity,    bool IsActive); public record ProductDetailsDto(    int Id,    string Name,    string? Description,    decimal Price,    int StockQuantity,    bool IsActive,    DateTime CreatedAtUtc); public class ProductCreateDto {    public string Name { get; set; } = string.Empty;    public string? Description { get; set; }    public decimal Price { get; set; }    public int StockQuantity { get; set; } } public class ProductUpdateDto : ProductCreateDto {    public bool IsActive { get; set; } }

Input models can use attributes such as Required and Range. Attribute-based validation is not enough by itself, however. Rules such as preventing two active products with the same name belong in the business layer because they depend on application behavior and existing data.

Step 2: Complete the database and service flow

After creating a migration for Product and configuring the connection string, the SQL Server database can be prepared. Applying migrations automatically may be convenient during development; in production, database changes should be handled as a controlled deployment step.

The business service retrieves data through the repository and projects it into DTOs. A list operation can look like this:

public async Task<IReadOnlyList<ProductListItemDto>> GetAllAsync(    CancellationToken cancellationToken) {    var products = await _repository.Query()        .AsNoTracking()        .Where(p => p.IsActive)        .OrderBy(p => p.Name)        .Select(p => new ProductListItemDto(            p.Id,            p.Name,            p.Price,            p.StockQuantity,            p.IsActive))        .ToListAsync(cancellationToken);    return products; }

AsNoTracking avoids unnecessary change-tracking work for read-only queries. Projecting to a DTO in the query also helps retrieve only the columns required by the list screen.

The create operation should enforce business rules in a predictable order:

  1. Reject an empty or excessively short product name.
  2. Reject prices below zero.
  3. Reject negative stock quantities.
  4. Prevent creation when an active product with the same name already exists.
  5. Map valid input to an entity and save the entity.

Use an application-specific error type or result model for expected business failures. This lets the controller distinguish a rule violation from an unexpected infrastructure failure instead of returning every problem as a generic server error.

Step 3: Expose the REST API

The API controller acts as an adapter between HTTP and the business service. It should read route values and request models, rely on framework validation, call the service, and return an appropriate HTTP result. It should not build SQL queries or contain the main business rules.

[ApiController] [Route("api/products")] public class ProductsController : ControllerBase {    private readonly IProductService _service;    public ProductsController(IProductService service)    {        _service = service;    }    [HttpGet]    public async Task<ActionResult<IReadOnlyList<ProductListItemDto>>> GetAll(        CancellationToken cancellationToken)    {        var result = await _service.GetAllAsync(cancellationToken);        return Ok(result);    }    [HttpGet("{id:int}")]    public async Task<ActionResult<ProductDetailsDto>> GetById(        int id,        CancellationToken cancellationToken)    {        var result = await _service.GetByIdAsync(id, cancellationToken);        return result is null ? NotFound() : Ok(result);    }    [HttpPost]    public async Task<ActionResult<ProductDetailsDto>> Create(        ProductCreateDto request,        CancellationToken cancellationToken)    {        var result = await _service.CreateAsync(request, cancellationToken);        return CreatedAtAction(nameof(GetById), new { id = result.Id }, result);    } }

Update and delete endpoints can follow the same pattern. A successful create operation commonly returns 201 Created; a missing resource returns 404 NotFound; invalid input may return 400 BadRequest or 422 Unprocessable Entity. The important point is consistency across the API.

Step 4: Connect the web client to the API

Keep HTTP calls inside a dedicated client class. This prevents web controllers and views from becoming responsible for serialization, URLs, and response handling. In current .NET applications, HttpClientFactory is a suitable way to configure and manage typed or named HTTP clients.

public interface IProductApiClient {    Task<IReadOnlyList<ProductListItemDto>> GetAllAsync(        CancellationToken cancellationToken);    Task CreateAsync(ProductCreateDto request,        CancellationToken cancellationToken); } public class ProductApiClient : IProductApiClient {    private readonly HttpClient _httpClient;    public ProductApiClient(HttpClient httpClient)    {        _httpClient = httpClient;    }    public async Task<IReadOnlyList<ProductListItemDto>> GetAllAsync(        CancellationToken cancellationToken)    {        var result = await _httpClient.GetFromJsonAsync<            IReadOnlyList<ProductListItemDto>>(                "api/products", cancellationToken);        return result ?? Array.Empty<ProductListItemDto>();    }    public async Task CreateAsync(ProductCreateDto request,        CancellationToken cancellationToken)    {        using var response = await _httpClient.PostAsJsonAsync(            "api/products", request, cancellationToken);        response.EnsureSuccessStatusCode();    } }

The web controller can request the data and pass it to a view model or Razor view:

public class ProductsController : Controller {    private readonly IProductApiClient _client;    public ProductsController(IProductApiClient client)    {        _client = client;    }    public async Task<IActionResult> Index(        CancellationToken cancellationToken)    {        var products = await _client.GetAllAsync(cancellationToken);        return View(products);    } }

The complete flow is now visible: the browser calls the web application, the web application calls the REST API, and the API uses the business and data access layers. If the web application and API run on different origins, review CORS, HTTPS, authentication headers, and environment-specific base addresses.

Step 5: Verify the administration workflow

Run the following end-to-end scenario:

  1. Confirm that the SQL Server connection works and that the Products table exists.
  2. Call GET /api/products with an HTTP client or the API documentation interface.
  3. Send a valid product to POST /api/products.
  4. Open the web administration page and verify that the new product appears.
  5. Change the product price or stock quantity.
  6. Deactivate or delete the product and verify the expected result on the next list request.

After each step, check that logs do not contain passwords, tokens, or other sensitive values. Request identifiers, endpoint names, elapsed time, and outcome status are useful diagnostic information. Users should receive understandable error messages rather than stack traces or database exceptions.

Common mistakes

  • Connecting directly to the database from the web layer: This mixes responsibilities and makes the API boundary meaningless.
  • Returning entities directly as JSON: This can expose internal fields, create serialization cycles, and produce fragile public contracts.
  • Ignoring HTTP status codes: Treating every response as successful causes the interface to display incorrect information.
  • Validating only in the browser: Because an API can be called independently, server-side validation is mandatory.
  • Tracking every query: Read-only list operations can waste resources when change tracking is unnecessary.
  • Dropping cancellation tokens: Long database work may continue even after the original request has been cancelled.
  • Returning vague API errors: The web client should distinguish validation, authorization, not-found, and infrastructure failures.

Practice exercise

Extend the project with the following features:

  1. Add a Category entity and a product-category relationship.
  2. Create an API endpoint that filters products by category.
  3. Add search and pagination parameters to the web administration page.
  4. Write a test for the duplicate active-product-name rule.
  5. Show a useful connection error when the API is unavailable.

Evaluate the result not only by whether the screen works, but also by checking layer boundaries, HTTP response consistency, validation, and behavior when dependencies fail.

Conclusion

This lesson completed the data flow from SQL Server to the browser. We separated entities from DTOs, kept data access and business rules in their respective layers, exposed REST endpoints through a controller, and connected the web client through HttpClient.

Real projects may add search, pagination, role-based authorization, caching, background processing, messaging, and distributed observability. The architectural principle remains the same: every layer should have a clear responsibility, communication should use explicit contracts, and important user scenarios should be verified end to end.

You can now approach a .NET solution not as a collection of isolated controllers and screens, but as a maintainable system in which data is designed, validated, persisted, exposed, and consumed through a controlled flow.

Sources