USAMA IRFAN

Senior Full-Stack & AI Engineer

Skip to main content
USAMA+IRFAN®
Back to Blog
Jun 14, 2025·9 min read

Build a Clean CRUD API with .NET, MediatR, and NSwag

Build a Clean CRUD API with .NET, MediatR, and NSwag

This tutorial walks through creating a Todo API in ASP.NET Core (.NET 8) using Clean Architecture. We’ll use separate projects for Domain, Application, Infrastructure, and API layers, implement CRUD operations via MediatR (CQRS), persist data in Azure Cosmos DB using EF Core, and generate Swagger docs with NSwag.

Project Setup

  1. Create the Solution and Projects: Use the .NET CLI to set up a solution with four projects (Domain, Application, Infrastructure, API). For example:

    new sln -n TodoApp dotnet new classlib -n TodoApp.Domain dotnet new classlib -n TodoApp.Application dotnet new classlib -n TodoApp.Infrastructure dotnet new webapi -n TodoApp.API --use-controllers dotnet sln TodoApp.sln add TodoApp.Domain/TodoApp.Domain.csproj dotnet sln TodoApp.sln add TodoApp.Application/TodoApp.Application.csproj dotnet sln TodoApp.sln add TodoApp.Infrastructure/TodoApp.Infrastructure.csproj dotnet sln TodoApp.sln add TodoApp.API/TodoApp.API.csproj

    The --use-controllers flag ensures the Web API project uses controller classes learn.microsoft.com.

  • Clean Architecture Layers: By following Clean Architecture, the Domain (core) project contains only business entities and interfaces, with no references to other layers devblogs.microsoft.com. The Application layer implements use cases (commands/queries), the Infrastructure layer provides EF Core/Cosmos DB implementations, and the API project handles HTTP requests. This separation yields maintainability, testability, and loose coupling devblogs.microsoft.com.

    For example, our projects might have folder structure:

    TodoApp.Domain
    TodoApp.Application
    TodoApp.Infrastructure
    TodoApp.API
    • Domain: Entities (TodoItem) and domain interfaces.

    • Application: CQRS request/handler logic (MediatR).

    • Infrastructure: EF Core DbContext (Cosmos), repository implementations.

    • API: Controllers, Program.cs, and DI registration.

devblogs.microsoft.com.

Domain Layer – Defining the TodoItem Entity

In the Domain project, define the TodoItem entity as a simple C# class. This represents the core data model. Azure Cosmos DB (via EF Core) requires an id field for each documentlearn.microsoft.com. By naming the C# property Id, EF Core will map it to the Cosmos DB id property. For example:csharpCopyEditnamespace TodoApp.Domain.Entities { public class TodoItem { public string Id { get; set; } // Mapped to Cosmos DB "id" public string Title { get; set; } public bool IsCompleted { get; set; } } }

  • Primary Key (Id): EF Core will treat Id as the primary key (Cosmos DB’s unique id)learn.microsoft.com. Note that Cosmos DB does not auto-generate IDs, so we must assign Id explicitly in our code (e.g. via Guid.NewGuid().ToString()).

  • Other Properties: You can add data annotations (e.g. [Required]) for validation and documentation. In NSwag examples, a TodoItem class used [Required] on the name property to enrich Swagger UI learn.microsoft.com. In our example, Title and IsCompleted are plain properties.

By design, the Domain layer has no dependencies on EF Core or other layers devblogs.microsoft.com. It simply defines the entity shapes used by the rest of the app. learn.microsoft.com.

Infrastructure Layer – DbContext and Cosmos DB Configuration

In the Infrastructure project, implement the EF Core DbContext for Cosmos DB and map the domain entity to a Cosmos container: using Microsoft.EntityFrameworkCore; using TodoApp.Domain.Entities; namespace TodoApp.Infrastructure.Data { public class TodoDbContext : DbContext { public TodoDbContext(DbContextOptions<TodoDbContext> options) : base(options) { } public DbSet<TodoItem> TodoItems { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { // Map TodoItem to a Cosmos DB container named "TodoItems" modelBuilder.Entity<TodoItem>().ToContainer("TodoItems"); // Configure the partition key on 'Id' for efficient queries modelBuilder.Entity<TodoItem>().HasPartitionKey(t => t.Id); } } }

  • Container Mapping: By default EF Core maps all entities to one container named after the context. We explicitly set the container name to "TodoItems" using ToContainer learn.microsoft.com. This creates/uses a Cosmos container for TodoItem documents.

  • Partition Key: We use Id as the partition key (via HasPartitionKey) learn.microsoft.com. Cosmos DB requires a partition key for scalability; here we choose the Id string. In production, choose a partitioning strategy suited to your queries.

  • EF Core Cosmos Provider: Register EF Core Cosmos provider by adding the Microsoft.EntityFrameworkCore.Cosmos NuGet package, then configuring the context in Program.cs (API project).

In the API project’s Program.cs, wire up the context with Cosmos DB connection details: builder.Services.AddDbContext<TodoDbContext>(options => options.UseCosmos( builder.Configuration["Cosmos:Endpoint"], builder.Configuration["Cosmos:Key"], databaseName: "TodoDb" )); Here we pass the Cosmos endpoint URI, key, and database name to UseCosmos learn.microsoft.com. Store the endpoint/key securely (e.g. in appsettings.json or Azure Key Vault). The TodoDbContext will then create the required container(s) on first use. learn.microsoft.com.

Application Layer – MediatR CQRS for CRUD

In the Application project, implement CRUD logic using MediatR (the Mediator pattern) and the CQRS approach. Each operation is defined as a request (command/query) and a corresponding handler. First, install the MediatR NuGet package.

  1. Create a Todo (Command): Define a request object for creation:

    public class CreateTodoItemCommand : IRequest<string> { public string Title { get; set; } }

    Then implement its handler:

    public class CreateTodoItemCommandHandler : IRequestHandler<CreateTodoItemCommand, string> { private readonly TodoDbContext _context; public CreateTodoItemCommandHandler(TodoDbContext context) => _context = context; public async Task<string> Handle(CreateTodoItemCommand req, CancellationToken ct) { var item = new TodoItem { Id = Guid.NewGuid().ToString(), Title = req.Title, IsCompleted = false }; _context.TodoItems.Add(item); await _context.SaveChangesAsync(); return item.Id; // return new ID } }

  2. Read Todos (Queries): For retrieving data, define queries. For example, get all items:

    public class GetAllTodosQuery : IRequest<List<TodoItem>> { } public class GetAllTodosQueryHandler : IRequestHandler<GetAllTodosQuery, List<TodoItem>> { private readonly TodoDbContext _context; public GetAllTodosQueryHandler(TodoDbContext context) => _context = context; public async Task<List<TodoItem>> Handle(GetAllTodosQuery query, CancellationToken ct) { return await _context.TodoItems.ToListAsync(); } }

    And get by ID:

    public class GetTodoByIdQuery : IRequest<TodoItem> { public string Id { get; } public GetTodoByIdQuery(string id) => Id = id; } public class GetTodoByIdQueryHandler : IRequestHandler<GetTodoByIdQuery, TodoItem> { private readonly TodoDbContext _context; public GetTodoByIdQueryHandler(TodoDbContext context) => _context = context; public async Task<TodoItem> Handle(GetTodoByIdQuery query, CancellationToken ct) { return await _context.TodoItems.FindAsync(new[] { query.Id, query.Id }) ?? throw new KeyNotFoundException(); } }

    (Note: FindAsync requires both key and partition key; here we pass query.Id for both.)

  3. Update Todo (Command): A command to update:

    public class UpdateTodoCommand : IRequest { public string Id { get; set; } public string Title { get; set; } public bool IsCompleted { get; set; } } public class UpdateTodoCommandHandler : IRequestHandler<UpdateTodoCommand> { private readonly TodoDbContext _context; public UpdateTodoCommandHandler(TodoDbContext context) => _context = context; public async Task<Unit> Handle(UpdateTodoCommand cmd, CancellationToken ct) { var item = await _context.TodoItems.FindAsync(new[] { cmd.Id, cmd.Id }); if (item is null) throw new KeyNotFoundException(); item.Title = cmd.Title; item.IsCompleted = cmd.IsCompleted; await _context.SaveChangesAsync(); return Unit.Value; } }

  4. Delete Todo (Command): A command to delete:

    public class DeleteTodoCommand : IRequest { public string Id { get; } public DeleteTodoCommand(string id) => Id = id; } public class DeleteTodoCommandHandler : IRequestHandler<DeleteTodoCommand> { private readonly TodoDbContext _context; public DeleteTodoCommandHandler(TodoDbContext context) => _context = context; public async Task<Unit> Handle(DeleteTodoCommand cmd, CancellationToken ct) { var item = await _context.TodoItems.FindAsync(new[] { cmd.Id, cmd.Id }); if (item == null) throw new KeyNotFoundException(); _context.TodoItems.Remove(item); await _context.SaveChangesAsync(); return Unit.Value; } }

  • Registering MediatR: In the API project’s Program.cs, add MediatR to DI so it can find these handlers. For example:

    builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

    This registers all IRequestHandler<…> in the assembly.

codewithmukesh.com learn.microsoft.com

API Layer – Controllers and Dependency Injection

In the API project, create controllers to handle HTTP requests and forward them via MediatR. For example, a TodoItemsController might look like: using MediatR; using Microsoft.AspNetCore.Mvc; using TodoApp.Application.Commands; using TodoApp.Application.Queries; [ApiController] [Route("api/[controller]")] public class TodoItemsController : ControllerBase { private readonly IMediator _mediator; public TodoItemsController(IMediator mediator) => _mediator = mediator; [HttpGet] public async Task<IActionResult> GetAll() { var items = await _mediator.Send(new GetAllTodosQuery()); return Ok(items); } [HttpGet("{id}")] public async Task<IActionResult> GetById(string id) { try { var item = await _mediator.Send(new GetTodoByIdQuery(id)); return Ok(item); } catch (KeyNotFoundException) { return NotFound(); } } [HttpPost] public async Task<IActionResult> Create([FromBody] CreateTodoItemCommand command) { var newId = await _mediator.Send(command); return CreatedAtAction(nameof(GetById), new { id = newId }, null); } [HttpPut("{id}")] public async Task<IActionResult> Update(string id, [FromBody] UpdateTodoCommand command) { if (id != command.Id) return BadRequest(); try { await _mediator.Send(command); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } } [HttpDelete("{id}")] public async Task<IActionResult> Delete(string id) { try { await _mediator.Send(new DeleteTodoCommand(id)); return NoContent(); } catch (KeyNotFoundException) { return NotFound(); } } } Key points:

  • The controller injects IMediator and uses mediator.Send(...) to dispatch requestscode-maze.com.

  • Each action corresponds to a MediatR request/handler defined earlier. This keeps controllers thin.

  • Standard HTTP responses (200, 201, 204, 404, etc.) are returned based on the handler result or exceptions.

For example, the GET and POST methods in the CodeMaze tutorial were implemented similarly with MediatR (using mediator.Send) code-maze.com.

NSwag – Swagger Documentation

Finally, enable Swagger/OpenAPI documentation using NSwag. First, install the NSwag.AspNetCore NuGet package. In Program.cs, add the OpenAPI services and middleware: // In builder.Services: builder.Services.AddOpenApiDocument(options => { options.PostProcess = doc => { doc.Info.Title = "Todo API"; doc.Info.Description = "API for managing Todo items"; doc.Info.Version = "v1"; }; }); // In app configuration: if (app.Environment.IsDevelopment()) { app.UseOpenApi(); // Serves the Swagger JSON at /swagger/v1/swagger.json app.UseSwaggerUi(); // Serves the Swagger UI at /swagger }

  • AddOpenApiDocument(): Registers the NSwag generator in DI learn.microsoft.com. The PostProcess delegate lets us customize metadata (title, version, etc.) learn.microsoft.com.

  • UseOpenApi(), UseSwaggerUi(): In development, this middleware exposes the Swagger JSON and UI learn.microsoft.com. By default, after running the app you can browse to http://localhost:<port>/swagger to view the UI.

NSwag supports XML comments, data annotations, and more to enrich the docs learn.microsoft.com. In our example, enabling [ProducesResponseType] and XML <summary> in controllers would make the Swagger UI more descriptive. learn.microsoft.com.

Conclusion

By following these steps, you create a well-structured .NET 8 Web API for Todo items. We separated concerns into Domain, Application, Infrastructure, and API layers (Clean Architecture) Visit Microsoft Documentation. The Domain holds the TodoItem model, the Infrastructure configures EF Core with Cosmos DB Visit Microsoft Documentation, the Application layer uses MediatR for CQRS-based CRUD logic codewithmukesh.com, and the API layer exposes controller endpoints wired to MediatR. Finally, NSwag auto-generates Swagger docs with just a few lines of setup learn.microsoft.com. This yields a clean, maintainable API with up-to-date documentation. Sources: Official docs and tutorials on EF Core with Azure Cosmos DB learn.microsoft.com, MediatR/CQRS best practices codewithmukesh.com, and NSwag/Swagger in ASP.NET Core learn.microsoft.com.

References

  1. Create a controller-based web API with ASP.NET Core | Microsoft Learn

  2. Next-Level Boilerplate: An Inside Look Into Our .Net Clean Architecture Repo - ISE Developer Blog

  3. Next-Level Boilerplate: An Inside Look Into Our .Net Clean Architecture Repo - ISE Developer Blog

  4. Azure Cosmos DB Provider - EF Core | Microsoft Learn

  5. Get started with NSwag and ASP.NET Core | Microsoft Learn

  6. Next-Level Boilerplate: An Inside Look Into Our .Net Clean Architecture Repo - ISE Developer Blog

  7. Modeling - Azure Cosmos DB Provider - EF Core | Microsoft Learn

  8. Modeling - Azure Cosmos DB Provider - EF Core | Microsoft Learn

  9. Azure Cosmos DB Provider - EF Core | Microsoft Learn

  10. CQRS and MediatR in ASP.NET Core - Building Scalable Systems - codewithmukesh

  11. Clean Architecture in .NET - Code Maze

  12. Get started with NSwag and ASP.NET Core | Microsoft Learn

  13. Get started with NSwag and ASP.NET Core | Microsoft Learn

  14. Get started with NSwag and ASP.NET Core | Microsoft Learn