Skip to content

Min API validation NRE when ValidationContext is not set on ValidateContext #61738

@sbomer

Description

@sbomer

Repro:

using Microsoft.AspNetCore.Http.Validation;
using Microsoft.Extensions.Options;
using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();
var app = builder.Build();

var model = new Model { Name = "Name" };

var validationOptions = app.Services.GetService<IOptions<ValidationOptions>>()!.Value;
if (!validationOptions.TryGetValidatableTypeInfo(typeof(Model), out var typeInfo))
{
    throw new InvalidOperationException("Type not found in validation options.");
}
var validateContext = new ValidateContext()
{
    ValidationOptions = validationOptions,
    // ValidationContext = new ValidationContext(model) // Uncomment this to fix it
};
await typeInfo.ValidateAsync(model, validateContext, CancellationToken.None);

[ValidatableType]
class Model
{
    [Required]
    public required string Name { get; init; }
}

This throws an exception:

Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.Http.Validation.ValidatablePropertyInfo.ValidateAsync(Object value, ValidateContext context, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Http.Validation.ValidatableTypeInfo.ValidateAsync(Object value, ValidateContext context, CancellationToken cancellationToken)
   at Program.<Main>$(String[] args) in /home/svbomer/src/test-apps/validationGen/Program.cs:line 21

Metadata

Metadata

Assignees

No one assigned

    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

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions