As enterprise ASP.NET Core MVC applications grow over months and years, organising code strictly by horizontal technical layers (Controllers/, Services/, Repositories/, ViewModels/) often creates friction. A single feature—such as creating an invoice or approving a leave request—forces developers to jump across half a dozen folders, while controllers accumulate validation rules, multi-service orchestration, logging, and transaction boilerplate. Over time, controllers turn into "fat controllers" that are hard to read, hard to test in isolation, and prone to unintended side effects when shared service methods are modified for one caller.
Vertical Slice Architecture reorganises the codebase around features (slices) rather than technical layers, keeping everything a feature needs—request contract, validator, handler, data access, and MVC view/action mapping—co-located in one cohesive place. Pairing vertical slices with CQRS (Command Query Responsibility Segregation) and MediatR pipeline behaviors gives MVC controllers a thin, uniform boundary while centralising cross-cutting concerns like validation, structured timing, and database transactions. This guide walks through structuring a vertical slice in ASP.NET Core MVC, wiring MediatR pipeline behaviours, and testing a slice end-to-end.
1. Architectural Blueprint & Slice Flow
In a vertical-slice MVC design, a controller action acts as an HTTP adapter: it binds input, checks ModelState, sends a command or query to ISender (MediatR), and translates the outcome into an MVC ViewResult, redirect, or JSON/problem response.
Concern |
Traditional Layered MVC |
Vertical Slice + CQRS + MediatR |
Code Organization |
Split horizontally by technical role (Controllers, Services, Repositories). |
Grouped vertically by feature (Features/Invoices/CreateInvoice/, Features/Invoices/GetInvoiceDetails/). |
Controller Role |
Often orchestrates multiple services, DTO mapping, and conditional logic. |
Thin HTTP entry/exit point; dispatches a single IRequest<TResponse> via ISender. |
Cross-Cutting Concerns |
Repeated inside service methods or handled via ad-hoc base classes/filters. |
Executed consistently around every handler via IPipelineBehavior<TRequest, TResponse>. |
HTTP Request (MVC Action / Form / API)
│
▼
[InvoicesController] ──> Builds Command / Query ──> [ISender.Send(request)]
│
▼
[MediatR Pipeline Behaviors]
1. ValidationBehavior (FluentValidation)
2. LoggingAndTimingBehavior
3. TransactionBehavior (EF Core)
│
▼
[CreateInvoiceCommandHandler]
│
▼
[ApplicationDbContext / Domain]
2. Domain Model & Slice Folder Layout
A typical feature-oriented layout inside an ASP.NET Core MVC project looks like this:
Plaintext
Features/
Invoices/
CreateInvoice/
CreateInvoiceCommand.cs
CreateInvoiceValidator.cs
CreateInvoiceHandler.cs
CreateInvoiceViewModel.cs
GetInvoiceSummary/
GetInvoiceSummaryQuery.cs
GetInvoiceSummaryHandler.cs
Controllers/
InvoicesController.cs
Behaviors/
ValidationBehavior.cs
LoggingBehavior.cs
TransactionBehavior.cs
Here are the core domain entities and contracts used across the slice:
C#
using MediatR;
public enum InvoiceStatus
{
Draft = 0,
Issued = 1,
Paid = 2,
Void = 3
}
public sealed class Invoice
{
public Guid Id { get; private set; }
public string InvoiceNumber { get; private set; } = string.Empty;
public string CustomerName { get; private set; } = string.Empty;
public decimal Subtotal { get; private set; }
public decimal TaxAmount { get; private set; }
public decimal TotalAmount => Subtotal + TaxAmount;
public InvoiceStatus Status { get; private set; }
public DateTimeOffset CreatedAtUtc { get; private set; }
private Invoice() { }
public static Invoice Create(
string invoiceNumber,
string customerName,
decimal subtotal,
decimal taxRate,
DateTimeOffset createdAtUtc)
{
if (string.IsNullOrWhiteSpace(invoiceNumber))
{
throw new ArgumentException("Invoice number is required.", nameof(invoiceNumber));
}
if (subtotal <= 0)
{
throw new ArgumentOutOfRangeException(nameof(subtotal), "Subtotal must be greater than zero.");
}
decimal taxAmount = Math.Round(subtotal * taxRate, 2, MidpointRounding.AwayFromZero);
return new Invoice
{
Id = Guid.NewGuid(),
InvoiceNumber = invoiceNumber.Trim().ToUpperInvariant(),
CustomerName = customerName.Trim(),
Subtotal = subtotal,
TaxAmount = taxAmount,
Status = InvoiceStatus.Issued,
CreatedAtUtc = createdAtUtc
};
}
}
public sealed record CreateInvoiceResult(
Guid InvoiceId,
string InvoiceNumber,
decimal TotalAmount,
InvoiceStatus Status
);
3. Implementing a Command Slice & Query Slice
Command Slice (CreateInvoice)
Commands express intent to change state and return a lightweight result or identifier.
C#
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
public sealed record CreateInvoiceCommand(
string InvoiceNumber,
string CustomerName,
decimal Subtotal,
decimal TaxRate
) : IRequest<CreateInvoiceResult>;
public sealed class CreateInvoiceValidator : AbstractValidator<CreateInvoiceCommand>
{
public CreateInvoiceValidator()
{
RuleFor(x => x.InvoiceNumber)
.NotEmpty()
.MaximumLength(32)
.Matches("^[A-Za-z0-9-]+$")
.WithMessage("Invoice number may only contain letters, digits, and hyphens.");
RuleFor(x => x.CustomerName)
.NotEmpty()
.MaximumLength(150);
RuleFor(x => x.Subtotal)
.GreaterThan(0m)
.LessThanOrEqualTo(100_000_000m);
RuleFor(x => x.TaxRate)
.InclusiveBetween(0m, 0.50m);
}
}
public sealed class CreateInvoiceHandler : IRequestHandler<CreateInvoiceCommand, CreateInvoiceResult>
{
private readonly ApplicationDbContext _dbContext;
private readonly TimeProvider _timeProvider;
public CreateInvoiceHandler(ApplicationDbContext dbContext, TimeProvider timeProvider)
{
_dbContext = dbContext;
_timeProvider = timeProvider;
}
public async Task<CreateInvoiceResult> Handle(
CreateInvoiceCommand request,
CancellationToken cancellationToken)
{
string normalizedNumber = request.InvoiceNumber.Trim().ToUpperInvariant();
bool exists = await _dbContext.Invoices
.AnyAsync(i => i.InvoiceNumber == normalizedNumber, cancellationToken);
if (exists)
{
throw new InvalidOperationException($"Invoice '{normalizedNumber}' already exists.");
}
var invoice = Invoice.Create(
normalizedNumber,
request.CustomerName,
request.Subtotal,
request.TaxRate,
_timeProvider.GetUtcNow());
_dbContext.Invoices.Add(invoice);
await _dbContext.SaveChangesAsync(cancellationToken);
return new CreateInvoiceResult(
invoice.Id,
invoice.InvoiceNumber,
invoice.TotalAmount,
invoice.Status);
}
}
Query Slice (GetInvoiceSummary)
Queries read state without mutating data and can project directly with AsNoTracking() for fast reads.
C#
using MediatR;
using Microsoft.EntityFrameworkCore;
public sealed record GetInvoiceSummaryQuery(Guid InvoiceId) : IRequest<InvoiceSummaryDto?>;
public sealed record InvoiceSummaryDto(
Guid Id,
string InvoiceNumber,
string CustomerName,
decimal TotalAmount,
string Status,
DateTimeOffset CreatedAtUtc
);
public sealed class GetInvoiceSummaryHandler : IRequestHandler<GetInvoiceSummaryQuery, InvoiceSummaryDto?>
{
private readonly ApplicationDbContext _dbContext;
public GetInvoiceSummaryHandler(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<InvoiceSummaryDto?> Handle(
GetInvoiceSummaryQuery request,
CancellationToken cancellationToken)
{
return await _dbContext.Invoices
.AsNoTracking()
.Where(i => i.Id == request.InvoiceId)
.Select(i => new InvoiceSummaryDto(
i.Id,
i.InvoiceNumber,
i.CustomerName,
i.Subtotal + i.TaxAmount,
i.Status.ToString(),
i.CreatedAtUtc))
.FirstOrDefaultAsync(cancellationToken);
}
}
4. MediatR Pipeline Behaviors (Validation, Logging, Transactions)
Pipeline behaviors wrap await next() in order of registration. Below are three practical behaviors:
ValidationBehavior<TRequest, TResponse>: Runs all registered FluentValidation validators for the request before the handler executes.
LoggingBehavior<TRequest, TResponse>: Logs request name, outcome, and elapsed duration.
TransactionBehavior<TRequest, TResponse>: Wraps command execution (requests marked with ITransactionalRequest) inside an explicit EF Core database transaction when no ambient transaction is already active.
C#
using System.Diagnostics;
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
public interface ITransactionalRequest { }
public sealed class ValidationBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
public ValidationBehavior(IEnumerable<IValidator<TRequest>> validators)
{
_validators = validators;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
if (!_validators.Any())
{
return await next(cancellationToken);
}
var context = new ValidationContext<TRequest>(request);
ValidationResult[] results = await Task.WhenAll(
_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
List<FluentValidation.Results.ValidationFailure> failures = results
.SelectMany(r => r.Errors)
.Where(f => f is not null)
.ToList();
if (failures.Count > 0)
{
throw new ValidationException(failures);
}
return await next(cancellationToken);
}
}
public sealed class LoggingBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : notnull
{
private readonly ILogger<LoggingBehavior<TRequest, TResponse>> _logger;
public LoggingBehavior(ILogger<LoggingBehavior<TRequest, TResponse>> logger)
{
_logger = logger;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
string requestName = typeof(TRequest).Name;
long startTimestamp = Stopwatch.GetTimestamp();
_logger.LogInformation("Handling {RequestName}", requestName);
try
{
TResponse response = await next(cancellationToken);
double elapsedMs = Stopwatch.GetElapsedTime(startTimestamp).TotalMilliseconds;
_logger.LogInformation(
"Completed {RequestName} in {ElapsedMs:F2} ms",
requestName,
elapsedMs);
return response;
}
catch (Exception ex)
{
double elapsedMs = Stopwatch.GetElapsedTime(startTimestamp).TotalMilliseconds;
_logger.LogWarning(
ex,
"Failed {RequestName} after {ElapsedMs:F2} ms",
requestName,
elapsedMs);
throw;
}
}
}
public sealed class TransactionBehavior<TRequest, TResponse>
: IPipelineBehavior<TRequest, TResponse>
where TRequest : ITransactionalRequest
{
private readonly ApplicationDbContext _dbContext;
public TransactionBehavior(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
if (_dbContext.Database.CurrentTransaction is not null)
{
return await next(cancellationToken);
}
await using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);
TResponse response = await next(cancellationToken);
await transaction.CommitAsync(cancellationToken);
return response;
}
}
(If you want CreateInvoiceCommand to participate in TransactionBehavior, have CreateInvoiceCommand implement ITransactionalRequest alongside IRequest<CreateInvoiceResult>.)
5. Thin MVC Controller & Programmatic Registration
MVC Controller (Controllers/InvoicesController.cs)
Notice how lean the controller stays: it maps the incoming view model to a command or query, delegates to ISender, and translates domain/validation exceptions into standard MVC responses.
C#
using System.ComponentModel.DataAnnotations;
using FluentValidation;
using MediatR;
using Microsoft.AspNetCore.Mvc;
public sealed class CreateInvoiceFormModel
{
[Required]
public string InvoiceNumber { get; set; } = string.Empty;
[Required]
public string CustomerName { get; set; } = string.Empty;
[Range(0.01, 100_000_000)]
public decimal Subtotal { get; set; }
[Range(0.0, 0.50)]
public decimal TaxRate { get; set; } = 0.17m;
}
[Route("invoices")]
public sealed class InvoicesController : Controller
{
private readonly ISender _sender;
public InvoicesController(ISender sender)
{
_sender = sender;
}
[HttpGet("create")]
public IActionResult Create()
{
return View(new CreateInvoiceFormModel());
}
[HttpPost("create")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
CreateInvoiceFormModel formModel,
CancellationToken cancellationToken)
{
if (!ModelState.IsValid)
{
return View(formModel);
}
var command = new CreateInvoiceCommand(
formModel.InvoiceNumber,
formModel.CustomerName,
formModel.Subtotal,
formModel.TaxRate);
try
{
CreateInvoiceResult created = await _sender.Send(command, cancellationToken);
TempData["SuccessMessage"] = $"Invoice {created.InvoiceNumber} created (Total: {created.TotalAmount:N2}).";
return RedirectToAction(nameof(Details), new { id = created.InvoiceId });
}
catch (ValidationException ex)
{
foreach (var error in ex.Errors)
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
return View(formModel);
}
catch (InvalidOperationException ex)
{
ModelState.AddModelError(nameof(formModel.InvoiceNumber), ex.Message);
return View(formModel);
}
}
[HttpGet("{id:guid}")]
public async Task<IActionResult> Details(Guid id, CancellationToken cancellationToken)
{
InvoiceSummaryDto? summary = await _sender.Send(new GetInvoiceSummaryQuery(id), cancellationToken);
if (summary is null)
{
return NotFound();
}
return View(summary);
}
}
Startup Registration (Program.cs)
Register MediatR handlers, open-generic pipeline behaviors, FluentValidation validators, and TimeProvider cleanly:
C#
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddValidatorsFromAssemblyContaining<CreateInvoiceValidator>();
builder.Services.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssemblyContaining<CreateInvoiceCommand>();
cfg.AddOpenBehavior(typeof(LoggingBehavior<,>));
cfg.AddOpenBehavior(typeof(ValidationBehavior<,>));
cfg.AddOpenBehavior(typeof(TransactionBehavior<,>));
});
builder.Services.AddControllersWithViews();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
6. Unit Testing a Slice Handler Without Heavy Mocking
Because CreateInvoiceHandler takes ApplicationDbContext and TimeProvider, you can test business rules and tax calculation directly against an in-memory/SQLite EF Core context or a fake TimeProvider without wiring up MVC controllers or HTTP contexts:
C#
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Time.Testing;
using Xunit;
public sealed class CreateInvoiceHandlerTests
{
[Fact]
public async Task Handle_ValidCommand_ComputesTaxAndPersistsInvoice()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
.Options;
await using var dbContext = new ApplicationDbContext(options);
var fakeTime = new FakeTimeProvider(new DateTimeOffset(2026, 11, 19, 10, 0, 0, TimeSpan.Zero));
var handler = new CreateInvoiceHandler(dbContext, fakeTime);
var command = new CreateInvoiceCommand(
InvoiceNumber: "inv-2026-001",
CustomerName: "Northwind Traders",
Subtotal: 1000.00m,
TaxRate: 0.18m);
CreateInvoiceResult result = await handler.Handle(command, CancellationToken.None);
Assert.Equal("INV-2026-001", result.InvoiceNumber);
Assert.Equal(1180.00m, result.TotalAmount);
Assert.Equal(InvoiceStatus.Issued, result.Status);
Assert.Equal(1, await dbContext.Invoices.CountAsync());
}
}
7. Conclusion
Organizing ASP.NET Core MVC features into Vertical Slices backed by CQRS and MediatR pipeline behaviors keeps controllers thin, cohesive, and focused on HTTP concerns. Feature logic stays localized instead of scattering across horizontal folders, cross-cutting rules like validation and logging run uniformly via pipeline behaviors, and individual command/query handlers can be tested cleanly against domain invariants and data access.
Join the conversation! Your thoughts help the community grow.