BenBristow.AspNetCore.DataValidationException 1.1.0

dotnet add package BenBristow.AspNetCore.DataValidationException --version 1.1.0
                    
NuGet\Install-Package BenBristow.AspNetCore.DataValidationException -Version 1.1.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BenBristow.AspNetCore.DataValidationException" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BenBristow.AspNetCore.DataValidationException" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="BenBristow.AspNetCore.DataValidationException" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BenBristow.AspNetCore.DataValidationException --version 1.1.0
                    
#r "nuget: BenBristow.AspNetCore.DataValidationException, 1.1.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BenBristow.AspNetCore.DataValidationException@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BenBristow.AspNetCore.DataValidationException&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=BenBristow.AspNetCore.DataValidationException&version=1.1.0
                    
Install as a Cake Tool

BenBristow.AspNetCore.DataValidationException

NuGet

A library for handling data validation exceptions in ASP.NET Core, with support for mapping domain properties to model properties.

Installation

dotnet add package BenBristow.AspNetCore.DataValidationException

Features

  • DataValidationException: A custom exception for capturing validation errors with property-level granularity
  • DataValidationExceptionFactory: A fluent builder for constructing validation exceptions
  • DataValidationMapsToPropertyAttribute: Map domain property names to model property names for seamless error mapping
  • ModelState Integration: Automatically add validation errors to ASP.NET Core ModelState

Usage

Basic Usage

using BenBristow.AspNetCore.DataValidationException.Exceptions;

// Create a validation exception with a single error
throw new DataValidationException("Invalid data");

// Create a validation exception with multiple errors
var errors = new Dictionary<string, IEnumerable<string>>
{
    { "Email", new[] { "Email is required", "Email must be valid" } },
    { "Password", new[] { "Password must be at least 8 characters" } }
};
throw new DataValidationException(errors);

Using the Factory Pattern

using BenBristow.AspNetCore.DataValidationException.Exceptions;

public class UserRegistrationModel
{
    public string Email { get; set; }
    public string Password { get; set; }
    public string Username { get; set; }
}

// Build and throw validation exception using the factory
var factory = new DataValidationExceptionFactory<UserRegistrationModel>();

factory
    .AddError(m => m.Email, "Email is required")
    .AddError(m => m.Email, "Email must be valid")
    .AddError(m => m.Password, "Password must be at least 8 characters")
    .AddError("General error not tied to a specific field");

throw factory.Create();

Mapping Domain Properties to Model Properties

When your domain model uses different property names than your API models, use the DataValidationMapsToPropertyAttribute to ensure errors are mapped correctly:

using BenBristow.AspNetCore.DataValidationException.Attributes;

public class UserApiModel
{
    [DataValidationMapsToProperty("EmailAddress")]  // Maps to domain property "EmailAddress"
    public string Email { get; set; }
    
    [DataValidationMapsToProperty("UserPassword")]  // Maps to domain property "UserPassword"
    public string Password { get; set; }
}

Adding Errors to ModelState

In your ASP.NET Core controller, catch the exception and add errors to ModelState:

using Microsoft.AspNetCore.Mvc;
using BenBristow.AspNetCore.DataValidationException.Exceptions;

[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    [HttpPost]
    public IActionResult CreateUser([FromBody] UserApiModel model)
    {
        try
        {
            // Your business logic that might throw DataValidationException
            _userService.CreateUser(model);
            return Ok();
        }
        catch (DataValidationException ex)
        {
            // Add validation errors to ModelState with property mapping
            ex.AddToModelState<UserApiModel>(ModelState);
            return BadRequest(ModelState);
        }
    }
}

The AddToModelState<T> method will automatically:

  1. Map domain property names to model property names using DataValidationMapsToPropertyAttribute
  2. Add all validation errors to the ModelState
  3. Preserve property names for unmapped properties

Complete Example

// Domain Service
public class UserService
{
    public void CreateUser(UserApiModel model)
    {
        var factory = new DataValidationExceptionFactory<UserApiModel>();
        
        if (string.IsNullOrEmpty(model.Email))
            factory.AddError(m => m.Email, "Email is required");
            
        if (model.Password?.Length < 8)
            factory.AddError(m => m.Password, "Password must be at least 8 characters");
            
        if (factory.HasErrors)
            throw factory.Create();
            
        // Continue with user creation...
    }
}

// API Model
public class UserApiModel
{
    [DataValidationMapsToProperty("EmailAddress")]
    public string Email { get; set; }
    
    [DataValidationMapsToProperty("UserPassword")]
    public string Password { get; set; }
}

// Controller
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
    private readonly UserService _userService;
    
    public UsersController(UserService userService)
    {
        _userService = userService;
    }
    
    [HttpPost]
    public IActionResult CreateUser([FromBody] UserApiModel model)
    {
        try
        {
            _userService.CreateUser(model);
            return Ok();
        }
        catch (DataValidationException ex)
        {
            ex.AddToModelState<UserApiModel>(ModelState);
            return BadRequest(ModelState);
        }
    }
}
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.1 is compatible. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.0 555 12/5/2025
1.0.1 222 12/4/2025
1.0.0 220 12/4/2025