Is there an existing issue for this?
Describe the bug
What's new in ASP.NET Core in .NET 10 in states the following for Validation support in Minimal APIs.
So consider the below sample code.
using System.ComponentModel.DataAnnotations;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
WebApplication app = builder. Build();
app.MapPost("/employees", (Employee employee) =>
{
return Results.Ok(employee);
});
app.Run();
public class Employee : IValidatableObject
{
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Name))
{
yield return new ValidationResult("Name cannot be null or empty.", [nameof(Name)]);
}
}
}
If I invoke the above endpoint with empty name,
POST {{WebApplication1_HostAddress}}/employees
Content-Type: application/json
{
"name": ""
}
The validation isn't kicking in as part of model binding.
I can do the validation manually,
app.MapPost("/employees", (Employee employee) =>
{
var validationResults = new List<ValidationResult>();
var validationContext = new ValidationContext(employee);
if (!Validator.TryValidateObject(employee, validationContext, validationResults, validateAllProperties: true))
{
return Results.ValidationProblem(validationResults.ToDictionary(
x => x.MemberNames.FirstOrDefault() ?? "",
x => new[] { x.ErrorMessage ?? "Invalid value." }));
}
return Results.Ok(employee);
});
But then I don't need to register builder.Services.AddValidation().
Expected Behavior
If validation is enabled via builder.Services.AddValidation(), as part of model binding on a type that implements IValidatableObject, validation should kick in automatically.
Steps To Reproduce
Given above
Exceptions (if any)
No response
.NET Version
10.0.100-preview.7.25380.108
Anything else?
No response
Is there an existing issue for this?
Describe the bug
What's new in ASP.NET Core in .NET 10 in states the following for Validation support in Minimal APIs.
So consider the below sample code.
If I invoke the above endpoint with empty
name,The validation isn't kicking in as part of model binding.
I can do the validation manually,
But then I don't need to register
builder.Services.AddValidation().Expected Behavior
If validation is enabled via
builder.Services.AddValidation(), as part of model binding on a type that implementsIValidatableObject, validation should kick in automatically.Steps To Reproduce
Given above
Exceptions (if any)
No response
.NET Version
10.0.100-preview.7.25380.108
Anything else?
No response