Skip to content

ASP.NET Core 10.0: Built-in Validation with IValidatableObject #63394

@jaliyaudagedara

Description

@jaliyaudagedara

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

What's new in ASP.NET Core in .NET 10 in states the following for Validation support in Minimal APIs.

Image

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

Metadata

Metadata

Assignees

Labels

area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-validationIssues related to model validation in minimal and controller-based APIs

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions