Class ValidationErrorsContext
Provides a context for collecting validation errors during JSON deserialization. Uses AsyncLocal to maintain thread-safe, request-scoped error collection.
public static class ValidationErrorsContext
- Inheritance
-
ValidationErrorsContext
- Inherited Members
Examples
using (ValidationErrorsContext.BeginScope())
{
// Deserialize JSON - errors are collected
var dto = JsonSerializer.Deserialize<CreateUserDto>(json, options);
// Check for collected errors
var error = ValidationErrorsContext.GetValidationError();
if (error is not null)
{
return Results.ValidationProblem(error);
}
}
Remarks
This class enables the pattern of collecting all validation errors from value objects during JSON deserialization, rather than failing on the first error. This allows returning a comprehensive list of validation failures to the client.
The context is automatically scoped per async operation, making it safe for use in concurrent web request scenarios.
Properties
HasErrors
Gets whether any validation errors have been collected in the current scope.
public static bool HasErrors { get; }
Property Value
Methods
BeginScope()
Begins a new validation error collection scope.
public static IDisposable BeginScope()
Returns
- IDisposable
An IDisposable that ends the scope when disposed.
Remarks
Always use this in a using statement or block to ensure proper cleanup. Nested scopes are supported; each scope maintains its own error collection.
GetValidationError()
Gets the aggregated validation error from the current scope, or null if no errors were collected.
public static ValidationError? GetValidationError()
Returns
- ValidationError
A ValidationError containing all collected field errors, or
nullif no validation errors were recorded.