
Welcome back! Earlier in our C# & .NET curriculum, we established our 4-layer Clean Architecture solution and wired up our PostgreSQL database with Entity Framework Core. Now we arrive at the question every developer asks when transitioning from console utilities to real-world systems: "I wrote C# classes that create and query products, but how does a user on an iOS/Android mobile app or a Next.js web browser actually invoke my C# code over the internet?"
The gateway that enables heterogeneous clients and external systems to communicate with your backend server securely over HTTP/HTTPS using a standardized data contract (JSON) is called a Web API (Application Programming Interface). At Digital HAT, our industrial B2B SaaS platforms (such as SafeWork360 and DHRevora) process millions of requests through hardened ASP.NET Core RESTful Web APIs. In this comprehensive guide, we will build an enterprise-grade Web API layer from scratch—covering its exact folder structure, the Program.cs middleware pipeline, Request/Response DTO contracts, centralized RFC 7807 exception handling, and a complete CRUD controller implementation line by line.
What You Will Build Step by Step in This Tutorial:
1. What Are Web APIs and REST Architecture? The Restaurant Waiter (API), Customer (Frontend), and Kitchen (Database) analogy.
2. The Complete Directory & File Tree of a production ASP.NET Core Web API project.
3. How the ASP.NET Core Middleware Pipeline works and why registration order inProgram.csis critical.
4. RESTful URL & HTTP Method (GET,POST,PUT,DELETE) design rules, idempotency, and HTTP status codes.
5. Why you must never expose Domain Entities directly—writing DTO (Data Transfer Object) contracts.
6. Full production C# implementation ofProductsController.cs,GlobalExceptionMiddleware.cs, andProgram.cs.
7. Live terminal verification withcurland the 5 most common Web API design mistakes.
1. What Is a Web API? (The Restaurant Analogy You Will Never Forget)
When you visit a restaurant, you cannot walk directly into the kitchen (Database / PostgreSQL) and open the refrigerator—doing so violates security boundaries, and you do not know the kitchen's internal recipes. Instead, you give your order from a structured menu to a waiter (Web API). The waiter validates your request, relays the instruction to the kitchen, and delivers the prepared dish back to your table on a standardized plate (JSON).
Because the waiter speaks a universal protocol (HTTPS + JSON), it does not matter whether the customer sitting at the table is a Next.js Web Application, an iOS/Android Mobile App, or a factory IoT Sensor—all clients interact with the exact same Web API and share the same core business rules:
┌──────────────────────────┐ HTTPS / JSON ┌────────────────────────────────────┐
│ Next.js Web Frontend │ ────────────────────────────► │ │
├──────────────────────────┤ HTTPS / JSON │ ASP.NET Core RESTful Web API │
│ iOS / Android Mobile App │ ────────────────────────────► │ (Kestrel + Middleware + Auth │
├──────────────────────────┤ HTTPS / JSON │ + Controllers + EF Core) │
│ ERP / B2B Partner Systems│ ────────────────────────────► │ │
└──────────────────────────┘ └─────────────────┬──────────────────┘
│ TCP / SSL (5432)
▼
┌────────────────────────────────────┐
│ PostgreSQL 16 Database │
└────────────────────────────────────┘
2. Complete Folder and File Structure of a Professional ASP.NET Core Web API
Let us inspect where every file belongs inside our presentation layer project, DigitalHat.Commerce.WebApi. Notice that this project contains zero SQL queries and zero domain invariants—its sole responsibility is handling HTTP transport concerns:
DigitalHat.Commerce.WebApi/
├── DigitalHat.Commerce.WebApi.csproj # Installed NuGet packages (Swashbuckle/OpenAPI, EF Core Design, etc.)
├── appsettings.json # Database connection strings, JWT settings, and Serilog levels
├── appsettings.Development.json # Local development overrides (localhost settings)
├── Program.cs # Application entry point: DI service registration & Middleware ordering
├── Controllers/ # HTTP API endpoints grouped by resource
│ ├── ProductsController.cs # /api/products (GET, POST, PUT, DELETE)
│ └── OrdersController.cs # /api/orders
├── Contracts/ (or DTOs/) # Incoming Request and outgoing Response JSON contracts
│ ├── CreateProductRequest.cs
│ ├── UpdateProductPriceRequest.cs
│ └── ProductResponse.cs
└── Middlewares/ # Cross-cutting HTTP middlewares
└── GlobalExceptionMiddleware.cs # Converts unhandled exceptions into RFC 7807 ProblemDetails JSON
3. How Does the ASP.NET Core Middleware Pipeline Work?
When an HTTP request arrives from a client, it does not jump straight into ProductsController! First, it passes sequentially through a chain of security and inspection gates (Middlewares) configured in Program.cs. If you register them in the wrong order—for example, placing Authorization before Authentication, or placing your Exception Handler at the bottom—your security checks will fail:
Incoming HTTP Request
│
▼ 1. GlobalExceptionMiddleware (Catches any downstream exception and returns safe 500/422 JSON)
▼ 2. ForwardedHeadersMiddleware (Reads the real client IP from X-Forwarded-For behind Nginx/Cloudflare)
▼ 3. HttpsRedirectionMiddleware (Redirects plain HTTP requests to encrypted HTTPS)
▼ 4. CorsMiddleware (Verifies whether the calling frontend origin is permitted)
▼ 5. RateLimiterMiddleware (Blocks abusive bots exceeding request quotas with HTTP 429)
▼ 6. AuthenticationMiddleware (Who are you? -> Validates the Authorization: Bearer JWT token)
▼ 7. AuthorizationMiddleware (Are you allowed? -> Checks [Authorize(Roles = "Admin")] policies)
▼ 8. Controllers (Endpoint) (Executes ProductsController.Create and serializes the JSON response!)
4. RESTful API URL and HTTP Method Design Standards
In poorly designed legacy APIs, you often see verb-heavy procedural URLs like /api/getProducts, /api/createNewProduct, or /api/deleteProductById. Under REST (Representational State Transfer) conventions, the URL is always a plural noun representing the resource collection (/api/products), while the HTTP Method (Verb) dictates the operation being performed:
| HTTP Method | Standard URL | Idempotent? | Responsibility | Expected HTTP Status Code |
|---|---|---|---|---|
GET |
/api/products?page=1&size=20 |
Yes (Safe) | Returns a paginated list of products without mutating state. | 200 OK |
GET |
/api/products/{id} |
Yes (Safe) | Retrieves a single product resource by its unique GUID. | 200 OK (or 404 Not Found if missing) |
POST |
/api/products |
No | Creates a brand-new product resource. | 201 Created + Location Header (or 400 Bad Request) |
PUT |
/api/products/{id}/price |
Yes | Updates an existing product's attributes or unit price. | 200 OK or 204 No Content (or 404 Not Found) |
DELETE |
/api/products/{id} |
Yes | Deletes or soft-deactivates the specified product. | 204 No Content (or 404 Not Found) |
Architectural Note — What Does "Idempotent" Mean?
An HTTP operation is idempotent if executing the exact same request five times in a row produces the same server state as executing it once.GET,PUT, andDELETEare idempotent (setting a product's price to18500.00five times still leaves its price at18500.00). However,POSTis not idempotent—sending the samePOST /api/productsrequest five times creates five separate product records unless protected by an idempotency key!
5. Step-by-Step Implementation: DTO Contracts, Controller, Exception Middleware, and Program.cs
Step 5.1: Contracts/ProductContracts.cs (Why We Always Use DTOs)
Our database entity class Product may contain internal columns such as wholesale cost, supplier tax ID, or soft-delete timestamps that external clients must never see. Furthermore, binding an EF Core entity directly to an [HttpPost] action exposes your API to Mass Assignment (Over-Posting) vulnerabilities where an attacker injects internal fields into the JSON payload. Therefore, we strictly accept Request DTOs and return Response DTOs:
// File Path: src/DigitalHat.Commerce.WebApi/Contracts/ProductContracts.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace DigitalHat.Commerce.WebApi.Contracts;
// 1. JSON payload sent by the client when creating a product (POST /api/products):
public record CreateProductRequest(
[Required(ErrorMessage = "Product name is required.")]
[StringLength(200, MinimumLength = 2, ErrorMessage = "Product name must be between 2 and 200 characters.")]
string Name,
[Required(ErrorMessage = "Stock Keeping Unit (SKU) is required.")]
[StringLength(64, MinimumLength = 3)]
string Sku,
[Range(0.01, 10000000, ErrorMessage = "Unit price must be greater than zero.")]
decimal UnitPrice,
[Range(0, 1000000, ErrorMessage = "Stock quantity cannot be negative.")]
int StockQuantity
);
// 2. JSON payload sent by the client when updating a product's price (PUT /api/products/{id}/price):
public record UpdateProductPriceRequest(
[Range(0.01, 10000000, ErrorMessage = "New unit price must be greater than zero.")]
decimal NewUnitPrice
);
// 3. Safe JSON contract returned to web and mobile clients:
public record ProductResponse(
Guid Id,
string Name,
string Sku,
decimal UnitPrice,
int StockQuantity,
bool IsInStock,
DateTimeOffset CreatedAt
);
Step 5.2: Controllers/ProductsController.cs (Complete 5-Endpoint CRUD Implementation)
Now let us open Controllers/ProductsController.cs and implement all five REST endpoints—listing, single lookup, creation, price update, and soft deletion—with detailed inline documentation:
// File Path: src/DigitalHat.Commerce.WebApi/Controllers/ProductsController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DigitalHat.Commerce.Application.Abstractions.Repositories;
using DigitalHat.Commerce.Domain.Entities;
using DigitalHat.Commerce.WebApi.Contracts;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DigitalHat.Commerce.WebApi.Controllers;
[ApiController] // Enables automatic model validation (HTTP 400) and JSON body binding
[Route("api/[controller]")] // Route template: /api/products
[Produces("application/json")]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _productRepository;
// Inject our repository abstraction via constructor Dependency Injection:
public ProductsController(IProductRepository productRepository)
{
_productRepository = productRepository;
}
// 1. LIST ALL ACTIVE PRODUCTS (GET /api/products)
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<ProductResponse>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetAll(CancellationToken ct)
{
var products = await _productRepository.GetAllActiveAsync(ct);
var response = products.Select(MapToResponse).ToList();
return Ok(response); // Returns HTTP 200 OK with a JSON array
}
// 2. GET SINGLE PRODUCT BY ID (GET /api/products/{id})
[HttpGet("{id:guid}")]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
{
var product = await _productRepository.GetByIdAsync(id, ct);
if (product is null)
{
// Return a standard HTTP 404 Not Found payload when the resource does not exist:
return NotFound(new
{
status = StatusCodes.Status404NotFound,
title = "Resource Not Found",
detail = $"Product with ID={id} was not found."
});
}
return Ok(MapToResponse(product));
}
// 3. CREATE A NEW PRODUCT (POST /api/products)
[HttpPost]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create([FromBody] CreateProductRequest request, CancellationToken ct)
{
// Our Domain entity enforces business invariants inside its constructor:
var product = new Product(request.Name, request.Sku, request.UnitPrice, request.StockQuantity);
await _productRepository.AddAsync(product, ct);
await _productRepository.SaveChangesAsync(ct);
var response = MapToResponse(product);
// Returns HTTP 201 Created and populates the Location header (/api/products/{id})!
return CreatedAtAction(nameof(GetById), new { id = product.Id }, response);
}
// 4. UPDATE PRODUCT PRICE (PUT /api/products/{id}/price)
[HttpPut("{id:guid}/price")]
[ProducesResponseType(typeof(ProductResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdatePrice(
Guid id,
[FromBody] UpdateProductPriceRequest request,
CancellationToken ct)
{
var product = await _productRepository.GetByIdAsync(id, ct);
if (product is null)
{
return NotFound(new { message = $"Product with ID={id} was not found." });
}
// Mutate state through our rich domain method rather than public property setters:
product.UpdatePrice(request.NewUnitPrice);
await _productRepository.SaveChangesAsync(ct);
return Ok(MapToResponse(product));
}
// 5. DEACTIVATE / SOFT-DELETE PRODUCT (DELETE /api/products/{id})
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken ct)
{
var product = await _productRepository.GetByIdAsync(id, ct);
if (product is null)
{
return NotFound(new { message = $"Product with ID={id} was not found." });
}
product.Deactivate();
await _productRepository.SaveChangesAsync(ct);
// Standard REST response for successful deletion with no response body:
return NoContent();
}
private static ProductResponse MapToResponse(Product product) => new(
product.Id,
product.Name,
product.Sku,
product.UnitPrice,
product.StockQuantity,
IsInStock: product.StockQuantity > 0,
product.CreatedAt
);
}
Step 5.3: Middlewares/GlobalExceptionMiddleware.cs (RFC 7807 ProblemDetails Error Handling)
Wrapping every controller action in repetitive try / catch blocks clutters your codebase. Instead, we write a centralized exception-handling middleware that intercepts unhandled exceptions across the entire pipeline, logs the full diagnostic context internally, and returns a clean RFC 7807 ProblemDetails JSON payload without leaking sensitive stack traces or database details:
// File Path: src/DigitalHat.Commerce.WebApi/Middlewares/GlobalExceptionMiddleware.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace DigitalHat.Commerce.WebApi.Middlewares;
public class GlobalExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionMiddleware> _logger;
public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (ArgumentException ex)
{
// Translate domain invariant violations into HTTP 422 Unprocessable Entity:
_logger.LogWarning(ex, "Domain business rule violation: {Message}", ex.Message);
await WriteProblemDetailsAsync(context, StatusCodes.Status422UnprocessableEntity, "Business Rule Violation", ex.Message);
}
catch (Exception ex)
{
// Log the full exception internally, but never leak stack traces to external clients!
_logger.LogError(ex, "Unhandled server exception on path {Path}", context.Request.Path);
await WriteProblemDetailsAsync(
context,
StatusCodes.Status500InternalServerError,
"Internal Server Error",
"An unexpected error occurred while processing your request. Please try again later.");
}
}
private static async Task WriteProblemDetailsAsync(HttpContext context, int statusCode, string title, string detail)
{
context.Response.StatusCode = statusCode;
context.Response.ContentType = "application/problem+json";
var problem = new ProblemDetails
{
Status = statusCode,
Title = title,
Detail = detail,
Instance = context.Request.Path
};
await context.Response.WriteAsJsonAsync(problem);
}
}
Step 5.4: Wiring Services and the Middleware Pipeline in Program.cs
// File Path: src/DigitalHat.Commerce.WebApi/Program.cs
using DigitalHat.Commerce.Infrastructure;
using DigitalHat.Commerce.WebApi.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
// 1. Dependency Injection Service Registrations
builder.Services.AddInfrastructure(builder.Configuration);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// 2. HTTP Middleware Pipeline (Execution Order Is Critical!)
app.UseMiddleware<GlobalExceptionMiddleware>();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
6. Testing Our Web API Live from the Terminal (curl)
After starting the server with dotnet run --project src/DigitalHat.Commerce.WebApi, you can explore the interactive OpenAPI documentation at http://localhost:5000/swagger or send a live POST request from your terminal using curl:
curl -i -X POST "http://localhost:5000/api/products" \
-H "Content-Type: application/json" \
-d '{
"name": "SafeWork360 Enterprise Field Safety License",
"sku": "DH-SW360-2026",
"unitPrice": 18500.00,
"stockQuantity": 50
}'
# HTTP 201 Created Response Returned by Kestrel:
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: http://localhost:5000/api/products/8f9d2a10-4c11-4e89-9a21-0192837465ab
{
"id": "8f9d2a10-4c11-4e89-9a21-0192837465ab",
"name": "SafeWork360 Enterprise Field Safety License",
"sku": "DH-SW360-2026",
"unitPrice": 18500.00,
"stockQuantity": 50,
"isInStock": true,
"createdAt": "2026-03-29T10:15:30+00:00"
}
7. The 5 Most Common Web API Engineering Mistakes
- Exposing Database Entities Directly Instead of DTOs: Coupling your public JSON schema to EF Core entities leaks sensitive columns and breaks mobile apps whenever you rename a database column.
- Returning HTTP
200 OKwith{ "success": false }on Errors: This violates HTTP semantics and breaks frontend error interceptors and API gateways. Always return proper status codes (400,404,422,500). - Omitting
CancellationTokenin Controller Actions: PassingCancellationToken ctdown to EF Core allows PostgreSQL to abort expensive queries immediately if the user closes their browser tab. - Mutating Server State Inside a
GETEndpoint: Browsers, CDNs, and web crawlers prefetchGETlinks freely. State changes must strictly usePOST,PUT,PATCH, orDELETE. - Returning Unbounded Collections Without Pagination: Serializing 500,000 rows in a single
GET /api/productscall will exhaust server memory and trigger connection timeouts.
8. Next Lesson: How to Communicate with APIs (HTTP Packet Anatomy, JSON, JWT, and Next.js / C# Clients)
We have built a clean, standards-compliant ASP.NET Core Web API! In Part 2 of this series, we switch to the client side: how do you consume this API securely from a Next.js / TypeScript web application and from another C# microservice using IHttpClientFactory, attach JWT Bearer Tokens, and solve CORS errors? Click the "Next Lesson in Series (Part 02)" card below to continue!
Did you find this engineering guide helpful?
Give it a like or share it with your team and network.