Home / Security / Bulletproof Input Validation with Noundry Guardian
Security

Bulletproof Input Validation with Noundry Guardian

Stop bad data at the door. Learn how to use Guardian's fluent guard clauses to validate API inputs, domain models, and service parameters — failing fast with clear, actionable error messages.

G
Chef George
February 5, 2026 15 mins Beginner 503 views

The Problem

Your API accepts a CreateOrderRequest and passes it straight to the service layer. A null email slips through, a negative price sneaks in, and an empty product list crashes the database insert three layers deep. The stack trace is useless — you're debugging in the wrong place.

You need validation that fails fast, fails loudly, and fails at the boundary — not buried inside business logic.

Ingredients

Noundry.Guardian

vlatest

Fluent guard clause library for input validation

.NET 10 SDK

v10.0

Target framework for the project

Just one package — Guardian is lightweight and dependency-free.

Preparation

dotnet add package Noundry.Guardian

2. Add the using directive

Every file that validates input needs just one import:

using Noundry.Guardian;

That's it — no configuration, no DI registration, no setup. Guardian is ready to use immediately.

The Code

Guardian's API follows a simple pattern: Guard.Against.{Rule}(value). Every method either returns the validated value (so you can assign it inline) or throws an appropriate exception.

Let's build a real-world order processing system with validation at every layer.

Models/CreateOrderRequest.cs
namespace MyApp.Models;

public record CreateOrderRequest(
    string CustomerEmail,
    string ShippingAddress,
    List<OrderItemRequest> Items
);

public record OrderItemRequest(
    Guid ProductId,
    int Quantity,
    decimal UnitPrice
);
Services/OrderService.cs
using Noundry.Guardian;
using MyApp.Models;

namespace MyApp.Services;

public class OrderService
{
    public Order CreateOrder(CreateOrderRequest request)
    {
        // Validate the request exists
        Guard.Against.Null(request);

        // Validate email format with regex
        var email = Guard.Against.InvalidFormat(
            request.CustomerEmail,
            @"^[^@\s]+@[^@\s]+\.[^@\s]+$",
            message: "A valid email address is required");

        // Validate shipping address has meaningful content
        var address = Guard.Against.NullOrWhiteSpace(request.ShippingAddress);
        address = Guard.Against.InvalidLength(address, 10, 500);

        // Validate the items collection isn't empty
        var items = Guard.Against.NullOrEmpty(request.Items);

        // Validate each line item
        var orderItems = new List<OrderItem>();
        foreach (var item in items)
        {
            Guard.Against.DefaultStruct(item.ProductId);
            Guard.Against.NegativeOrZero(item.Quantity);
            Guard.Against.NegativeOrZero(item.UnitPrice);
            Guard.Against.GreaterThan(item.UnitPrice, 999999.99m);

            orderItems.Add(new OrderItem(
                item.ProductId, item.Quantity, item.UnitPrice));
        }

        // Business rule: order total must be within bounds
        var total = orderItems.Sum(i => i.Quantity * i.UnitPrice);
        Guard.Against.GreaterThan(total, 1_000_000m,
            message: $"Order total ${total:N2} exceeds maximum of $1,000,000");

        return new Order(Guid.NewGuid(), email, address, orderItems, total);
    }
}
Endpoints/OrderEndpoints.cs
using MyApp.Models;
using MyApp.Services;

namespace MyApp.Endpoints;

public static class OrderEndpoints
{
    public static void MapOrderEndpoints(this WebApplication app)
    {
        app.MapPost("/api/orders", (CreateOrderRequest request, OrderService service) =>
        {
            try
            {
                var order = service.CreateOrder(request);
                return Results.Created($"/api/orders/{order.Id}", order);
            }
            catch (ArgumentNullException ex)
            {
                return Results.BadRequest(new { error = $"Missing: {ex.ParamName}" });
            }
            catch (ArgumentOutOfRangeException ex)
            {
                return Results.BadRequest(new { error = ex.Message });
            }
            catch (ArgumentException ex)
            {
                return Results.BadRequest(new { error = ex.Message });
            }
        });
    }
}
Models/Order.cs
using Noundry.Guardian;

namespace MyApp.Models;

public class Order
{
    public Guid Id { get; }
    public string CustomerEmail { get; }
    public string ShippingAddress { get; }
    public IReadOnlyList<OrderItem> Items { get; }
    public decimal Total { get; }

    public Order(Guid id, string email, string address,
        List<OrderItem> items, decimal total)
    {
        Id = Guard.Against.DefaultStruct(id);
        CustomerEmail = Guard.Against.NullOrWhiteSpace(email);
        ShippingAddress = Guard.Against.NullOrWhiteSpace(address);
        Items = Guard.Against.NullOrEmpty(items).ToList().AsReadOnly();
        Total = Guard.Against.NegativeOrZero(total);
    }
}

public record OrderItem(Guid ProductId, int Quantity, decimal UnitPrice);

Plating

Your inputs are now validated at every boundary:

  • API layer catches and returns 400 Bad Request with clear messages
  • Service layer validates business rules before any database calls
  • Domain models enforce their own invariants via constructor validation
  • Automatic parameter names via [CallerArgumentExpression] — no magic strings

Guardian's key advantages:

  • Zero configuration — install and use
  • Methods return validated values for inline assignment
  • Appropriate exception types (ArgumentNullException, ArgumentOutOfRangeException, ArgumentException)
  • Guard.Against.Condition() for any custom business rule

Next steps:

  • Combine with Noundry.Tuxedo for validated database operations
  • Use Guard.Against.NotInEnum() for state machine transitions
  • Add global exception middleware to standardize error responses

Was this recipe helpful?

G

Chef George

.NET Architect & Head Chef

25+ years crafting enterprise C# solutions. Creator of the Noundry platform. Passionate about clean architecture, cloud-agnostic deployments, and code that cooks.