This is a great request for a comprehensive C# ASP.NET Core web API boilerplate using vertical slice architecture. Let me create a well-structured example that demonstrates:
- Vertical slice architecture principles
- Clear folder structure
- CQRS pattern for commands and queries
- Dependency injection
- Error handling
- Validation
- Logging
- Database context
- Multiple features to show the pattern
I'll create:
- Project structure
- Startup configuration
- Sample features (Orders, Customers, Products)
- Request/Response DTOs
- Commands and Handlers
- Controllers
- Database layer
- Middleware
- Extensions
Let me build this comprehensively:
C# ASP.NET Core Vertical Slice Architecture Boilerplate
Here's a complete, production-ready boilerplate:
Project Structure
src/
├── YourApp.API/
│ ├── Features/
│ │ ├── Orders/
│ │ │ ├── CreateOrder/
│ │ │ │ ├── CreateOrderCommand.cs
│ │ │ │ ├── CreateOrderCommandHandler.cs
│ │ │ │ ├── CreateOrderRequest.cs
│ │ │ │ ├── CreateOrderResponse.cs
│ │ │ │ └── CreateOrderController.cs
│ │ │ ├── GetOrder/
│ │ │ │ ├── GetOrderQuery.cs
│ │ │ │ ├── GetOrderQueryHandler.cs
│ │ │ │ ├── GetOrderResponse.cs
│ │ │ │ └── GetOrderController.cs
│ │ │ ├── OrderEntity.cs
│ │ │ └── OrderRepository.cs
│ │ ├── Customers/
│ │ │ ├── CreateCustomer/
│ │ │ │ ├── CreateCustomerCommand.cs
│ │ │ │ ├── CreateCustomerCommandHandler.cs
│ │ │ │ ├── CreateCustomerRequest.cs
│ │ │ │ ├── CreateCustomerResponse.cs
│ │ │ │ └── CreateCustomerController.cs
│ │ │ ├── GetCustomer/
│ │ │ │ ├── GetCustomerQuery.cs
│ │ │ │ ├── GetCustomerQueryHandler.cs
│ │ │ │ ├── GetCustomerResponse.cs
│ │ │ │ └── GetCustomerController.cs
│ │ │ ├── CustomerEntity.cs
│ │ │ └── CustomerRepository.cs
│ │ └── Products/
│ │ ├── CreateProduct/
│ │ ├── GetProduct/
│ │ ├── ProductEntity.cs
│ │ └── ProductRepository.cs
│ ├── Infrastructure/
│ │ ├── Data/
│ │ │ ├── ApplicationDbContext.cs
│ │ │ └── DbContextFactory.cs
│ │ ├── Behaviors/
│ │ │ ├── LoggingBehavior.cs
│ │ │ ├── ValidationBehavior.cs
│ │ │ └── TransactionBehavior.cs
│ │ ├── Middleware/
│ │ │ ├── GlobalExceptionHandler.cs
│ │ │ └── RequestLoggingMiddleware.cs
│ │ └── Extensions/
│ │ └── ServiceCollectionExtensions.cs
│ ├── Common/
│ │ ├── Interfaces/
│ │ │ ├── ICommand.cs
│ │ │ ├── ICommandHandler.cs
│ │ │ ├── IQuery.cs
│ │ │ ├── IQueryHandler.cs
│ │ │ └── IRepository.cs
│ │ ├── Result/
│ │ │ └── Result.cs
│ │ ├── Exceptions/
│ │ │ ├── DomainException.cs
│ │ │ ├── ValidationException.cs
│ │ │ └── NotFoundException.cs
│ │ └── Constants/
│ │ └── AppConstants.cs
│ ├── Program.cs
│ └── appsettings.json
└── YourApp.sln
Core Files
1. Program.cs
using YourApp.API.Infrastructure.Data;
using YourApp.API.Infrastructure.Extensions;
using YourApp.API.Infrastructure.Middleware;
var builder = WebApplication.CreateBuilder(args);
// Add services
builder.Services
.AddControllers()
.AddNewtonsoftJson();
builder.Services.AddSwaggerGen();
builder.Services.AddHealthChecks();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
// Add custom services
builder.Services.AddApplicationServices(builder.Configuration);
builder.Services.AddInfrastructure(builder.Configuration);
var app = builder.Build();
// Configure middleware
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors("AllowAll");
app.UseRouting();
app.UseAuthorization();
// Custom middleware
app.UseMiddleware<GlobalExceptionHandler>();
app.UseMiddleware<RequestLoggingMiddleware>();
app.MapControllers();
app.MapHealthChecks("/health");
app.MapGet("/", () => Results.Ok("Welcome to the API")).WithName("Root").WithOpenApi();
await MigrateDatabase(app);
app.Run();
static async Task MigrateDatabase(WebApplication app)
{
using (var scope = app.Services.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await dbContext.Database.MigrateAsync();
}
}
2. Common/Interfaces
// ICommand.cs
namespace YourApp.API.Common.Interfaces;
public interface ICommand
{
}
public interface ICommand<out TResponse> : ICommand
{
}
// ICommandHandler.cs
namespace YourApp.API.Common.Interfaces;
public interface ICommandHandler<in TCommand> where TCommand : ICommand
{
Task<Result> Handle(TCommand command, CancellationToken cancellationToken);
}
public interface ICommandHandler<in TCommand, TResponse> where TCommand : ICommand<TResponse>
{
Task<Result<TResponse>> Handle(TCommand command, CancellationToken cancellationToken);
}
// IQuery.cs
namespace YourApp.API.Common.Interfaces;
public interface IQuery<out TResponse>
{
}
// IQueryHandler.cs
namespace YourApp.API.Common.Interfaces;
public interface IQueryHandler<in TQuery, TResponse> where TQuery : IQuery<TResponse>
{
Task<Result<TResponse>> Handle(TQuery query, CancellationToken cancellationToken);
}
// IRepository.cs
namespace YourApp.API.Common.Interfaces;
public interface IRepository<TEntity> where TEntity : class
{
Task<TEntity?> GetByIdAsync(int id, CancellationToken cancellationToken = default);
Task<IEnumerable<TEntity>> GetAllAsync(CancellationToken cancellationToken = default);
Task AddAsync(TEntity entity, CancellationToken cancellationToken = default);
Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default);
Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default);
Task SaveChangesAsync(CancellationToken cancellationToken = default);
}
3. Common/Result
namespace YourApp.API.Common.Result;
public class Result
{
protected Result(bool isSuccess, string error)
{
IsSuccess = isSuccess;
Error = error;
}
public bool IsSuccess { get; }
public string Error { get; }
public static Result Ok() => new(true, string.Empty);
public static Result Fail(string error) => new(false, error);
public static Result<T> Ok<T>(T data) => new(true, string.Empty, data);
public static Result<T> Fail<T>(string error) => new(false, error, default);
}
public class Result<T> : Result
{
protected internal Result(bool isSuccess, string error, T? data)
: base(isSuccess, error)
{
Data = data;
}
public T? Data { get; }
}
4. Common/Exceptions
namespace YourApp.API.Common.Exceptions;
public class DomainException : Exception
{
public DomainException(string message) : base(message) { }
}
public class NotFoundException : DomainException
{
public NotFoundException(string resource, int id)
: base($"{resource} with ID {id} not found") { }
}
public class ValidationException : DomainException
{
public ValidationException(Dictionary<string, string[]> errors)
: base("One or more validation errors occurred.")
{
Errors = errors;
}
public Dictionary<string, string[]> Errors { get; }
}
5. Infrastructure/Data
// ApplicationDbContext.cs
using Microsoft.EntityFrameworkCore;
using YourApp.API.Features.Orders;
using YourApp.API.Features.Customers;
using YourApp.API.Features.Products;
namespace YourApp.API.Infrastructure.Data;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) { }
// Orders
public DbSet<OrderEntity> Orders { get; set; } = default!;
// Customers
public DbSet<CustomerEntity> Customers { get; set; } = default!;
// Products
public DbSet<ProductEntity> Products { get; set; } = default!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Configure Order
modelBuilder.Entity<OrderEntity>()
.HasKey(x => x.Id);
modelBuilder.Entity<OrderEntity>()
.Property(x => x.OrderNumber)
.IsRequired()
.HasMaxLength(50);
modelBuilder.Entity<OrderEntity>()
.HasOne(x => x.Customer)
.WithMany()
.HasForeignKey(x => x.CustomerId)
.OnDelete(DeleteBehavior.Cascade);
// Configure Customer
modelBuilder.Entity<CustomerEntity>()
.HasKey(x => x.Id);
modelBuilder.Entity<CustomerEntity>()
.Property(x => x.Email)
.IsRequired()
.HasMaxLength(256);
// Configure Product
modelBuilder.Entity<ProductEntity>()
.HasKey(x => x.Id);
modelBuilder.Entity<ProductEntity>()
.Property(x => x.Name)
.IsRequired()
.HasMaxLength(200);
}
}
6. Infrastructure/Middleware
// GlobalExceptionHandler.cs
using System.Text.Json;
using YourApp.API.Common.Exceptions;
namespace YourApp.API.Infrastructure.Middleware;
public class GlobalExceptionHandler
{
private readonly RequestDelegate _next;
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(RequestDelegate next, ILogger<GlobalExceptionHandler> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "An unhandled exception occurred");
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
var response = new ErrorResponse();
switch (exception)
{
case NotFoundException notFound:
context.Response.StatusCode = StatusCodes.Status404NotFound;
response = new ErrorResponse { Message = notFound.Message, StatusCode = 404 };
break;
case ValidationException validation:
context.Response.StatusCode = StatusCodes.Status400BadRequest;
response = new ErrorResponse
{
Message = validation.Message,
StatusCode = 400,
Errors = validation.Errors
};
break;
case DomainException domain:
context.Response.StatusCode = StatusCodes.Status400BadRequest;
response = new ErrorResponse { Message = domain.Message, StatusCode = 400 };
break;
default:
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
response = new ErrorResponse
{
Message = "An internal server error occurred",
StatusCode = 500
};
break;
}
return context.Response.WriteAsJsonAsync(response);
}
}
public class ErrorResponse
{
public int StatusCode { get; set; }
public string Message { get; set; } = string.Empty;
public Dictionary<string, string[]>? Errors { get; set; }
}
// RequestLoggingMiddleware.cs
namespace YourApp.API.Infrastructure.Middleware;
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
var request = context.Request;
_logger.LogInformation("Request: {Method} {Path}", request.Method, request.Path);
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
await _next(context);
stopwatch.Stop();
_logger.LogInformation("Response: {StatusCode} completed in {ElapsedMilliseconds}ms",
context.Response.StatusCode, stopwatch.ElapsedMilliseconds);
}
}
7. Infrastructure/Behaviors
// ValidationBehavior.cs
using FluentValidation;
using MediatR;
using YourApp.API.Common.Exceptions;
using YourApp.API.Common.Interfaces;
using YourApp.API.Common.Result;
namespace YourApp.API.Infrastructure.Behaviors;
public class ValidationBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly IEnumerable<IValidator<TRequest>> _validators;
private readonly ILogger<ValidationBehavior<TRequest, TResponse>> _logger;
public ValidationBehavior(
IEnumerable<IValidator<TRequest>> validators,
ILogger<ValidationBehavior<TRequest, TResponse>> logger)
{
_validators = validators;
_logger = logger;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
if (!_validators.Any())
{
return await next();
}
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(
_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults
.Where(r => r.Errors.Count != 0)
.SelectMany(r => r.Errors)
.ToList();
if (failures.Count != 0)
{
_logger.LogWarning("Validation failed for {Request}", typeof(TRequest).Name);
var errorsDictionary = failures
.GroupBy(e => e.PropertyName)
.ToDictionary(
failureGroup => failureGroup.Key,
failureGroup => failureGroup.Select(f => f.ErrorMessage).ToArray());
throw new ValidationException(errorsDictionary);
}
return await next();
}
}
// LoggingBehavior.cs
using MediatR;
namespace YourApp.API.Infrastructure.Behaviors;
public class LoggingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
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)
{
_logger.LogInformation("Handling {Request}", typeof(TRequest).Name);
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var result = await next();
stopwatch.Stop();
_logger.LogInformation("{Request} completed in {ElapsedMilliseconds}ms",
typeof(TRequest).Name, stopwatch.ElapsedMilliseconds);
return result;
}
}
// TransactionBehavior.cs
using MediatR;
using YourApp.API.Infrastructure.Data;
namespace YourApp.API.Infrastructure.Behaviors;
public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>
{
private readonly ApplicationDbContext _dbContext;
private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger;
public TransactionBehavior(
ApplicationDbContext dbContext,
ILogger<TransactionBehavior<TRequest, TResponse>> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<TResponse> Handle(
TRequest request,
RequestHandlerDelegate<TResponse> next,
CancellationToken cancellationToken)
{
var strategy = _dbContext.Database.CreateExecutionStrategy();
return await strategy.ExecuteAsync(async () =>
{
using var transaction = await _dbContext.Database.BeginTransactionAsync(cancellationToken);
try
{
var response = await next();
await transaction.CommitAsync(cancellationToken);
return response;
}
catch (Exception ex)
{
_logger.LogError(ex, "Transaction failed for {Request}", typeof(TRequest).Name);
await transaction.RollbackAsync(cancellationToken);
throw;
}
});
}
}
8. Infrastructure/Extensions
// ServiceCollectionExtensions.cs
using FluentValidation;
using MediatR;
using Microsoft.EntityFrameworkCore;
using YourApp.API.Infrastructure.Behaviors;
using YourApp.API.Infrastructure.Data;
namespace YourApp.API.Infrastructure.Extensions;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddApplicationServices(
this IServiceCollection services,
IConfiguration configuration)
{
// MediatR
services.AddMediatR(config =>
{
config.RegisterServicesFromAssemblyContaining(typeof(Program));
config.AddOpenBehavior(typeof(LoggingBehavior<,>));
config.AddOpenBehavior(typeof(ValidationBehavior<,>));
config.AddOpenBehavior(typeof(TransactionBehavior<,>));
});
// FluentValidation
services.AddValidatorsFromAssemblyContaining(typeof(Program));
// AutoMapper
services.AddAutoMapper(typeof(Program));
return services;
}
public static IServiceCollection AddInfrastructure(
this IServiceCollection services,
IConfiguration configuration)
{
// Database
var connectionString = configuration.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(typeof(Program).Assembly.FullName);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelaySeconds: 10, errorNumbersToAdd: null);
}));
// Repositories - Add your repositories here
services.AddScoped(typeof(IRepository<>), typeof(GenericRepository<>));
return services;
}
}
public interface IRepository<TEntity> where TEntity : class
{
Task<TEntity?> GetByIdAsync(int id, CancellationToken cancellationToken = default);
Task<IEnumerable<TEntity>> GetAllAsync(CancellationToken cancellationToken = default);
Task AddAsync(TEntity entity, CancellationToken cancellationToken = default);
Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default);
Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default);
Task SaveChangesAsync(CancellationToken cancellationToken = default);
}
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected readonly ApplicationDbContext _context;
public GenericRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<TEntity?> GetByIdAsync(int id, CancellationToken cancellationToken = default)
{
return await _context.Set<TEntity>().FindAsync(new object[] { id }, cancellationToken: cancellationToken);
}
public async Task<IEnumerable<TEntity>> GetAllAsync(CancellationToken cancellationToken = default)
{
return await _context.Set<TEntity>().ToListAsync(cancellationToken);
}
public async Task AddAsync(TEntity entity, CancellationToken cancellationToken = default)
{
await _context.Set<TEntity>().AddAsync(entity, cancellationToken);
await SaveChangesAsync(cancellationToken);
}
public async Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default)
{
_context.Set<TEntity>().Update(entity);
await SaveChangesAsync(cancellationToken);
}
public async Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default)
{
_context.Set<TEntity>().Remove(entity);
await SaveChangesAsync(cancellationToken);
}
public async Task SaveChangesAsync(CancellationToken cancellationToken = default)
{
await _context.SaveChangesAsync(cancellationToken);
}
}
Feature Examples
Feature 1: Create Order
// Features/Orders/CreateOrder/CreateOrderCommand.cs
using MediatR;
using YourApp.API.Common.Result;
namespace YourApp.API.Features.Orders.CreateOrder;
public class CreateOrderCommand : IRequest<Result<CreateOrderResponse>>
{
public int CustomerId { get; set; }
public List<OrderItemDto> Items { get; set; } = new();
}
public class OrderItemDto
{
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
// Features/Orders/CreateOrder/CreateOrderRequest.cs
namespace YourApp.API.Features.Orders.CreateOrder;
public class CreateOrderRequest
{
public int CustomerId { get; set; }
public List<OrderItemRequest> Items { get; set; } = new();
}
public class OrderItemRequest
{
public int ProductId { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
// Features/Orders/CreateOrder/CreateOrderResponse.cs
namespace YourApp.API.Features.Orders.CreateOrder;
public class CreateOrderResponse
{
public int OrderId { get; set; }
public string OrderNumber { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public decimal TotalAmount { get; set; }
}
// Features/Orders/CreateOrder/CreateOrderCommandHandler.cs
using AutoMapper;
using MediatR;
using YourApp.API.Common.Exceptions;
using YourApp.API.Common.Result;
using YourApp.API.Infrastructure.Data;
using YourApp.API.Infrastructure.Extensions;
namespace YourApp.API.Features.Orders.CreateOrder;
public class CreateOrderCommandHandler : IRequestHandler<CreateOrderCommand, Result<CreateOrderResponse>>
{
private readonly IRepository<OrderEntity> _orderRepository;
private readonly IRepository<CustomerEntity> _customerRepository;
private readonly IRepository<ProductEntity> _productRepository;
private readonly IMapper _mapper;
private readonly ILogger<CreateOrderCommandHandler> _logger;
public CreateOrderCommandHandler(
IRepository<OrderEntity> orderRepository,
IRepository<CustomerEntity> customerRepository,
IRepository<ProductEntity> productRepository,
IMapper mapper,
ILogger<CreateOrderCommandHandler> logger)
{
_orderRepository = orderRepository;
_customerRepository = customerRepository;
_productRepository = productRepository;
_mapper = mapper;
_logger = logger;
}
public async Task<Result<CreateOrderResponse>> Handle(
CreateOrderCommand command,
CancellationToken cancellationToken)
{
_logger.LogInformation("Creating order for customer {CustomerId}", command.CustomerId);
// Validate customer exists
var customer = await _customerRepository.GetByIdAsync(command.CustomerId, cancellationToken);
if (customer is null)
{
throw new NotFoundException(nameof(CustomerEntity), command.CustomerId);
}
// Validate products exist and get pricing
foreach (var item in command.Items)
{
var product = await _productRepository.GetByIdAsync(item.ProductId, cancellationToken);
if (product is null)
{
throw new NotFoundException(nameof(ProductEntity), item.ProductId);
}
if (product.StockQuantity < item.Quantity)
{
throw new DomainException($"Insufficient stock for product {product.Name}");
}
}
// Create order
var order = new OrderEntity
{
OrderNumber = GenerateOrderNumber(),
CustomerId = command.CustomerId,
Customer = customer,
OrderDate = DateTime.UtcNow,
Items = command.Items
.Select(i => new OrderItemEntity
{
ProductId = i.ProductId,
Quantity = i.Quantity,
Price = i.Price
})
.ToList(),
Status = OrderStatus.Pending,
TotalAmount = command.Items.Sum(x => x.Price * x.Quantity)
};
await _orderRepository.AddAsync(order, cancellationToken);
_logger.LogInformation("Order {OrderNumber} created successfully", order.OrderNumber);
return Result.Ok(new CreateOrderResponse
{
OrderId = order.Id,
OrderNumber = order.OrderNumber,
CreatedAt = order.OrderDate,
TotalAmount = order.TotalAmount
});
}
private string GenerateOrderNumber()
{
return $"ORD-{DateTime.UtcNow:yyyyMMddHHmmss}-{Guid.NewGuid().ToString()[..8]}";
}
}
// Features/Orders/CreateOrder/CreateOrderValidator.cs
using FluentValidation;
namespace YourApp.API.Features.Orders.CreateOrder;
public class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
public CreateOrderCommandValidator()
{
RuleFor(x => x.CustomerId)
.GreaterThan(0)
.WithMessage("Customer ID must be greater than 0");
RuleFor(x => x.Items)
.NotEmpty()
.WithMessage("Order must contain at least one item");
RuleForEach(x => x.Items)
.SetValidator(new OrderItemValidator());
}
}
public class OrderItemValidator : AbstractValidator<OrderItemDto>
{
public OrderItemValidator()
{
RuleFor(x => x.ProductId)
.GreaterThan(0)
.WithMessage("Product ID must be greater than 0");
RuleFor(x => x.Quantity)
.GreaterThan(0)
.WithMessage("Quantity must be greater than 0");
RuleFor(x => x.Price)
.GreaterThan(0)
.WithMessage("Price must be greater than 0");
}
}
// Features/Orders/CreateOrder/CreateOrderController.cs
using MediatR;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
namespace YourApp.API.Features.Orders.CreateOrder;
[ApiController]
[Route("api/[controller]")]
public class CreateOrderController : ControllerBase
{
private readonly IMediator _mediator;
private readonly IMapper _mapper;
private readonly ILogger<CreateOrderController> _logger;
public CreateOrderController(
IMediator mediator,
IMapper mapper,
ILogger<CreateOrderController> logger)
{
_mediator = mediator;
_mapper = mapper;
_logger = logger;
}
[HttpPost]
[ProducesResponseType(typeof(CreateOrderResponse), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> CreateOrder(
[FromBody] CreateOrderRequest request,
CancellationToken cancellationToken)
{
var command = _mapper.Map<CreateOrderCommand>(request);
var result = await _mediator.Send(command, cancellationToken);
return CreatedAtAction(nameof(CreateOrder), new { id = result.Data?.OrderId }, result.Data);
}
}
// Features/Orders/CreateOrder/MappingProfile.cs
using AutoMapper;
namespace YourApp.API.Features.Orders.CreateOrder;
public class CreateOrderMappingProfile : Profile
{
public CreateOrderMappingProfile()
{
CreateMap<CreateOrderRequest, CreateOrderCommand>();
CreateMap<OrderItemRequest, OrderItemDto>();
}
}
Feature 2: Get Order
// Features/Orders/GetOrder/GetOrderQuery.cs
using MediatR;
using YourApp.API.Common.Result;
namespace YourApp.API.Features.Orders.GetOrder;
public class GetOrderQuery : IRequest<Result<GetOrderResponse>>
{
public int OrderId { get; set; }
}
// Features/Orders/GetOrder/GetOrderResponse.cs
namespace YourApp.API.Features.Orders.GetOrder;
public class GetOrderResponse
{
public int OrderId { get; set; }
public string OrderNumber { get; set; } = string.Empty;
public int CustomerId { get; set; }
public string CustomerName { get; set; } = string.Empty;
public DateTime OrderDate { get; set; }
public string Status { get; set; } = string.Empty;
public decimal TotalAmount { get; set; }
public List<OrderItemResponse> Items { get; set; } = new();
}
public class OrderItemResponse
{
public int ProductId { get; set; }
public string ProductName { get; set; } = string.Empty;
public int Quantity { get; set; }
public decimal Price { get; set; }
public decimal LineTotal { get; set; }
}
// Features/Orders/GetOrder/GetOrderQueryHandler.cs
using AutoMapper;
using MediatR;
using YourApp.API.Common.Exceptions;
using YourApp.API.Common.Result;
using YourApp.API.Infrastructure.Data;
using YourApp.API.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;
namespace YourApp.API.Features.Orders.GetOrder;
public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, Result<GetOrderResponse>>
{
private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper;
private readonly ILogger<GetOrderQueryHandler> _logger;
public GetOrderQueryHandler(
ApplicationDbContext dbContext,
IMapper mapper,
ILogger<GetOrderQueryHandler> logger)
{
_dbContext = dbContext;
_mapper = mapper;
_logger = logger;
}
public async Task<Result<GetOrderResponse>> Handle(GetOrderQuery query, CancellationToken cancellationToken)
{
_logger.LogInformation("Fetching order {OrderId}", query.OrderId);
var order = await _dbContext.Orders
.Include(o => o.Customer)
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.FirstOrDefaultAsync(o => o.Id == query.OrderId, cancellationToken);
if (order is null)
{
throw new NotFoundException(nameof(OrderEntity), query.OrderId);
}
var response = _mapper.Map<GetOrderResponse>(order);
return Result.Ok(response);
}
}
// Features/Orders/GetOrder/GetOrderValidator.cs
using FluentValidation;
namespace YourApp.API.Features.Orders.GetOrder;
public class GetOrderQueryValidator : AbstractValidator<GetOrderQuery>
{
public GetOrderQueryValidator()
{
RuleFor(x => x.OrderId)
.GreaterThan(0)
.WithMessage("Order ID must be greater than 0");
}
}
// Features/Orders/GetOrder/GetOrderController.cs
using MediatR;
using Microsoft.AspNetCore.Mvc;
namespace YourApp.API.Features.Orders.GetOrder;
[ApiController]
[Route("api")]
public class GetOrderController : ControllerBase
{
private readonly IMediator _mediator;
private readonly ILogger<GetOrderController> _logger;
public GetOrderController(IMediator mediator, ILogger<GetOrderController> logger)
{
_mediator = mediator;
_logger = logger;
}
[HttpGet("orders/{orderId}")]
[ProducesResponseType(typeof(GetOrderResponse), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetOrder(int orderId, CancellationToken cancellationToken)
{
var query = new GetOrderQuery { OrderId = orderId };
var result = await _mediator.Send(query, cancellationToken);
return Ok(result.Data);
}
}
// Features/Orders/GetOrder/MappingProfile.cs
using AutoMapper;
namespace YourApp.API.Features.Orders.GetOrder;
public class GetOrderMappingProfile : Profile
{
public GetOrderMappingProfile()
{
CreateMap<OrderEntity, GetOrderResponse>()
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.Status.ToString()))
.ForMember(dest => dest.CustomerName, opt => opt.MapFrom(src => src.Customer!.Name));
CreateMap<OrderItemEntity, OrderItemResponse>()
.ForMember(dest => dest.ProductName, opt => opt.MapFrom(src => src.Product!.Name))
.ForMember(dest => dest.LineTotal, opt => opt.MapFrom(src => src.Quantity * src.Price));
}
}
Feature 3: Create Customer
// Features/Customers/CreateCustomer/CreateCustomerCommand.cs
using MediatR;
using YourApp.API.Common.Result;
namespace YourApp.API.Features.Customers.CreateCustomer;
public class CreateCustomerCommand : IRequest<Result<CreateCustomerResponse>>
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
}
// Features/Customers/CreateCustomer/CreateCustomerRequest.cs
namespace YourApp.API.Features.Customers.CreateCustomer;
public class CreateCustomerRequest
{
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
}
// Features/Customers/CreateCustomer/CreateCustomerResponse.cs
namespace YourApp.API.Features.Customers.CreateCustomer;
public class CreateCustomerResponse
{
public int CustomerId { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
}
// Features/Customers/CreateCustomer/CreateCustomerCommandHandler.cs
using AutoMapper;
using MediatR;
using YourApp.API.Infrastructure.Data;
using YourApp.API.Infrastructure.Extensions;
namespace YourApp.API.Features.Customers.CreateCustomer;
public class CreateCustomerCommandHandler : IRequestHandler<CreateCustomerCommand, Result<CreateCustomerResponse>>
{
private readonly IRepository<CustomerEntity> _customerRepository;
private readonly IMapper _mapper;
private readonly ILogger<CreateCustomerCommandHandler> _logger;
public CreateCustomerCommandHandler(
IRepository<CustomerEntity> customerRepository,
IMapper mapper,
ILogger<CreateCustomerCommandHandler> logger)
{
_customerRepository = customerRepository;
_mapper = mapper;
_logger = logger;
}
public async Task<Result<CreateCustomerResponse>> Handle(
CreateCustomerCommand command,
CancellationToken cancellationToken)
{
_logger.LogInformation("Creating customer {Email}", command.Email);
var customer = new CustomerEntity
{
Name = command.Name,
Email = command.Email,
PhoneNumber = command.PhoneNumber,
Address = command.Address,
CreatedAt = DateTime.UtcNow
};
await _customerRepository.AddAsync(customer, cancellationToken);
_logger.LogInformation("Customer {CustomerId} created successfully", customer.Id);
return Result.Ok(new CreateCustomerResponse
{
CustomerId = customer.Id,
Name = customer.Name,
Email = customer.Email,
CreatedAt = customer.CreatedAt
});
}
}
// Features/Customers/CreateCustomer/CreateCustomerValidator.cs
using FluentValidation;
namespace YourApp.API.Features.Customers.CreateCustomer;
public class CreateCustomerCommandValidator : AbstractValidator<CreateCustomerCommand>
{
public CreateCustomerCommandValidator()
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Name is required")
.Length(2, 256).WithMessage("Name must be between 2 and 256 characters");
RuleFor(x => x.Email)
.NotEmpty().WithMessage("Email is required")
.EmailAddress().WithMessage("Email must be a valid email address");
RuleFor(x => x.PhoneNumber)
.NotEmpty().WithMessage("Phone number is required")
.Matches(@"^\+?[1-9]\d{1,14}$").WithMessage("Phone number is not valid");
RuleFor(x => x.Address)
.NotEmpty().WithMessage("Address is required")
.MaximumLength(500).WithMessage("Address must not exceed 500 characters");
}
}
// Features/Customers/CreateCustomer/CreateCustomerController.cs
using MediatR;
using Microsoft.AspNetCore.Mvc;
using AutoMapper;
namespace YourApp.API.Features.Customers.CreateCustomer;
[ApiController]
[Route("api/[controller]")]
public class CreateCustomerController : ControllerBase
{
private readonly IMediator _mediator;
private readonly IMapper _mapper;
private readonly ILogger<CreateCustomerController> _logger;
public CreateCustomerController(
IMediator mediator,
IMapper mapper,
ILogger<CreateCustomerController> logger)
{
_mediator = mediator;
_mapper = mapper;
_logger = logger;
}
[HttpPost]
[ProducesResponseType(typeof(CreateCustomerResponse), StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> CreateCustomer(
[FromBody] CreateCustomerRequest request,
CancellationToken cancellationToken)
{
var command = _mapper.Map<CreateCustomerCommand>(request);
var result = await _mediator.Send(command, cancellationToken);
return CreatedAtAction(nameof(CreateCustomer), new { id = result.Data?.CustomerId }, result.Data);
}
}
// Features/Customers/CreateCustomer/MappingProfile.cs
using AutoMapper;
namespace YourApp.API.Features.Customers.CreateCustomer;
public class CreateCustomerMappingProfile : Profile
{
public CreateCustomerMappingProfile()
{
CreateMap<CreateCustomerRequest, CreateCustomerCommand>();
}
}
Entity Models
// Features/Orders/OrderEntity.cs
using YourApp.API.Features.Customers;
namespace YourApp.API.Features.Orders;
public class OrderEntity
{
public int Id { get; set; }
public string OrderNumber { get; set; } = string.Empty;
public int CustomerId { get; set; }
public CustomerEntity? Customer { get; set; }
public DateTime OrderDate { get; set; }
public OrderStatus Status { get; set; }
public decimal TotalAmount { get; set; }
public List<OrderItemEntity> Items { get; set; } = new();
}
public class OrderItemEntity
{
public int Id { get; set; }
public int OrderId { get; set; }
public int ProductId { get; set; }
public ProductEntity? Product { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
}
public enum OrderStatus
{
Pending,
Processing,
Shipped,
Delivered,
Cancelled
}
// Features/Customers/CustomerEntity.cs
namespace YourApp.API.Features.Customers;
public class CustomerEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Email { get; set; } = string.Empty;
public string PhoneNumber { get; set; } = string.Empty;
public string Address { get; set; } = string.Empty;
public DateTime CreatedAt { get; set; }
public DateTime ModifiedAt { get; set; }
public bool IsActive { get; set; } = true;
}
// Features/Products/ProductEntity.cs
namespace YourApp.API.Features.Products;
public class ProductEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public decimal Price { get; set; }
public int StockQuantity { get; set; }
public DateTime CreatedAt { get; set; }
public bool IsActive { get; set; } = true;
}
appsettings.json
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=YourAppDB;Trusted_Connection=true;TrustServerCertificate=true;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.EntityFrameworkCore": "Warning",
"Microsoft.AspNetCore": "Warning"
},
"Console": {
"IncludeScopes": true
}
},
"AllowedHosts": "*",
"Jwt": {
"SecretKey": "your-super-secret-key-that-is-at-least-32-characters-long!",
"Issuer": "YourApp",
"Audience": "YourAppUsers",
"ExpireMinutes": 60
}
}
.csproj File
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="MediatR" Version="12.1.1" />
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
<PackageReference Include="FluentValidation.DependencyInjectionExtensions" Version="11.8.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="8.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.0" />
</ItemGroup>
</Project>
Key Features
✅ Vertical Slice Architecture - Each feature is self-contained
✅ CQRS Pattern - Separation of commands and queries
✅ MediatR - Request/response pattern
✅ FluentValidation - Strong validation
✅ AutoMapper - Object mapping
✅ Global Exception Handling - Centralized error management
✅ Logging - Integrated logging with behaviors
✅ Entity Framework Core - Strong ORM
✅ Dependency Injection - Built-in IoC
✅ Repository Pattern - Data access abstraction
✅ Transaction Management - Automatic transaction handling
✅ Health Checks - Application health monitoring
This boilerplate provides a solid foundation for building scalable, maintainable APIs!