July 29 2025
dotnet add package Carter
MyApi/
├── Program.cs
├── Endpoints/
│ └── ProductModule.cs
├── Models/
│ ├── Product.cs
│ └── ProductDto.cs
├── Validators/
│ └── CreateProductDtoValidator.cs
namespace MyApi.Models;
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; } = default!;
public decimal Price { get; set; }
}
namespace MyApi.Models;
public record CreateProductDto(string Name, decimal Price);
using FluentValidation;
using MyApi.Models;
namespace MyApi.Validators;
public class CreateProductDtoValidator : AbstractValidator<CreateProductDto>
{
public CreateProductDtoValidator()
{
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
RuleFor(x => x.Price).GreaterThan(0);
}
}
using Carter;
using FluentValidation;
using Mapster;
using Microsoft.AspNetCore.Http.HttpResults;
using MyApi.Models;
namespace MyApi.Endpoints;
public class ProductModule : ICarterModule
{
private static readonly List<Product> _products = [];
public void AddRoutes(IEndpointRouteBuilder app)
{
app.MapGet("/products", () => _products);
app.MapPost("/products", async (
CreateProductDto dto,
IValidator<CreateProductDto> validator) =>
{
var validationResult = await validator.ValidateAsync(dto);
if (!validationResult.IsValid)
{
var errors = validationResult.Errors
.ToDictionary(e => e.PropertyName, e => e.ErrorMessage);
return Results.BadRequest(errors);
}
var product = dto.ToProduct<Product>();
product.Id = Guid.NewGuid();
_products.Add(product);
return Results.Created($"/products/{product.Id}", product);
});
}
}
using Carter;
using FluentValidation;
using MyApi.Models;
using MyApi.Validators;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCarter();
builder.Services.AddScoped<IValidator<CreateProductDto>, CreateProductDtoValidator>();
var app = builder.Build();
app.MapCarter(); // This maps all Carter modules automatically
app.Run();
1. Design Patterns that Deliver
This isn’t just another design patterns book. Dive into real-world examples and practical solutions to real problems in real applications.Check out it here.
Go-to resource for understanding the core concepts of design patterns without the overwhelming complexity. In this concise and affordable ebook, I've distilled the essence of design patterns into an easy-to-digest format. It is a Beginner level. Check out it here.
Every Monday morning, I share 1 actionable tip on C#, .NET & Arcitecture topic, that you can use right away.
Join 17,150+ subscribers to improve your .NET Knowledge.
Subscribe to the TheCodeMan.net and be among the 17,150+ subscribers gaining practical tips and resources to enhance your .NET expertise.
Powered by EmailOctopus