Skip to content

Add tests for validating null values of minimal API parameters - #67395

Merged
Youssef1313 merged 29 commits into
dotnet:mainfrom
surya3655:67033-validation-attributes
Aug 6, 2026
Merged

Youssef1313 merged 29 commits into
dotnet:mainfrom
surya3655:67033-validation-attributes

Conversation

@surya3655

Copy link
Copy Markdown
Contributor

Description

This change fixes validation behavior for nullable parameters in minimal APIs.

Previously, validatable parameters could be skipped when the bound argument was null, which meant validation attributes were not evaluated for nullable parameters when no value was provided. In addition, ValidatableParameterInfo.ValidateAsync could return early for null values even when validation attributes were present.

This update changes the validation flow so that:

  • nullable parameters are still validated when the bound value is null
  • ValidationContext is created with a non-null placeholder instance
  • ValidateAsync only skips null values when there are no validation attributes to apply
  • regression tests cover nullable parameter validation scenarios

This ensures validation attributes continue to run for nullable parameters, including when no query value is supplied.

Output

Before:
image
image

After
image
image
image

Fixes #67033

@surya3655
surya3655 requested a review from halter73 as a code owner June 24, 2026 09:45
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Jun 24, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @surya3655. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@Youssef1313
Youssef1313 requested a review from oroztocil June 24, 2026 11:38
@Youssef1313 Youssef1313 added area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc feature-validation Issues related to model validation in minimal and controller-based APIs labels Jun 25, 2026
{
// A small struct to hold the validatable parameter details to avoid allocating arrays for parameters that don't need validation
private readonly record struct ValidatableParameterEntry(int Index, IValidatableParameterInfo Parameter, string Name);
private readonly record struct ValidatableParameterEntry(int Index, IValidatableParameterInfo Parameter, string Name, ParameterValidationTarget ValidationTarget);

@Youssef1313 Youssef1313 Jul 21, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think a new class (ParameterValidationTarget) is necessary here.

After few internal discussions, we decided to always use a throwaway object as the ObjectInstance for parameter validation (regardless of whether the value is or isn't null)

@surya3655

surya3655 commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor Author

@Youssef1313 , I tested the Minimal API validation with the latest main branch, but the validation is not working. The same validation works correctly in my existing source.
For example, when a validation rule restricts values to a specific range, the existing source correctly validates the input and rejects invalid values. However, with the latest main branch, all values are being accepted, which indicates that the validation is not being triggered.
Could you please confirm this issue and review my sample code below? Also, let me know if there is anything additional that needs to be added to reproduce or investigate the issue further.

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using BlazorUnitedApp;
using BlazorUnitedApp.Data;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
 
var builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveWebAssemblyComponents()
    .AddInteractiveServerComponents();
 
builder.Services.AddSingleton<WeatherForecastService>();
 
// ADD VALIDATION SERVICES - Required for MEV
builder.Services.AddValidation();
 
var app = builder.Build();
 
// CONFIGURE THE HTTP REQUEST PIPELINE.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see [Search - Microsoft Bing](https://aka.ms/aspnetcore-hsts.)
    app.UseHsts();
}
 
app.UseHttpsRedirection();
 
app.UseStaticFiles();
app.UseAntiforgery();
 
app.MapStaticAssets();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode()
    .AddInteractiveWebAssemblyRenderMode();
 
app.MapGet("/get", ([FromQuery, MyVal] int? id) =>
{
    return $"Hey {id?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "null"}";
});
app.MapGet("/set", ([FromQuery, MyVal] int id) =>
{
    return $"Hey {id.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? "null"}";
});
 
app.Run();
 
// CUSTOM VALIDATION ATTRIBUTE - Always fails for demonstration
internal class MyValAttribute : ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
    {
        string y = "old";
        // Only allow id == 1
        if (value is int intValue && intValue == 1)
        {
            return ValidationResult.Success; // ✅ passes when id=1
        }
        if (value is int intValue2)
        {
            y = intValue2.ToString(System.Globalization.CultureInfo.InvariantCulture);
        }
        else if (value is null)
        {
            y = "null";
        }
        else
        {
            y = value.ToString() ?? "unknown";
        }
 
        return new ValidationResult($"Validation failed: id must equal 1. but value is {y}"); // ❌ fails otherwise
    }
}

@Youssef1313

Youssef1313 commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

There is a build error here.

Overall, I'm not really sure if the added tests actually reach the ValidationEndpointFilter code path. In any cases, the new tests should belong to ValidationEndpointFilterFactoryTests and not RouteHandlerEndpointRouteBuilderExtensionsTest.

So please ensure the code builds correctly and the tests are passing. Once you get to a point where the tests are passing, try to revert the product change to validate if or not they are still passing. Even if they pass without a product change, we can happily merge a test-only change here (assuming no other tests cover the scenario).

@surya3655

Copy link
Copy Markdown
Contributor Author

@Youssef1313
Thanks for the clarification.

I updated/rebased the branch with latest main and reverted my product changes to verify whether the issue is already fixed. After resolving the build issue and testing the latest source again, I am still seeing the same behavior: Minimal API validation is not triggered for the sample.

In the sample, [MyVal] int? id should reject id=1 and id=2, but both values are accepted, and the custom validation attribute does not appear to be hit.

I’ll move the regression tests to ValidationEndpointFilterFactoryTests as suggested so they directly exercise the validation endpoint filter path. Before updating the product fix further, could you please confirm whether any additional setup is required for Minimal API validation on latest main, or whether this sample/configuration is expected to work as-is?

@Youssef1313

Copy link
Copy Markdown
Member

@surya3655 The current branch still doesn't build. It's best to get it to build successfully with tests passing to discuss this further.

};
}

private static ValidationContext CreateValidationContext(HttpContext httpContext, ValidatableParameterEntry entry, object? argument)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, we no longer create a ValidationContext here at all because of recent Microsoft.Extensions.Validation API changes.

@Youssef1313

Copy link
Copy Markdown
Member

@surya3655 The CI is failing because there are test failures. For example:

2026-08-03T04:29:42.8115819Z [xUnit.net 00:00:05.87]     Microsoft.AspNetCore.Builder.RouteHandlerEndpointRouteBuilderExtensionsTest.Validation_RunsRequiredAttribute_ForNullableValueType_WhenNoQueryParamProvided [FAIL]
2026-08-03T04:29:42.8116113Z [xUnit.net 00:00:05.87]       Assert.Equal() Failure: Values differ
2026-08-03T04:29:42.8116155Z [xUnit.net 00:00:05.87]       Expected: 400
2026-08-03T04:29:42.8116180Z [xUnit.net 00:00:05.87]       Actual:   200
2026-08-03T04:29:42.8116203Z [xUnit.net 00:00:05.87]       Stack Trace:
2026-08-03T04:29:42.8159659Z [xUnit.net 00:00:05.87]         /_/src/Http/Routing/test/UnitTests/Builder/RouteHandlerEndpointRouteBuilderExtensionsTest.cs(882,0): at Microsoft.AspNetCore.Builder.RouteHandlerEndpointRouteBuilderExtensionsTest.Validation_RunsRequiredAttribute_ForNullableValueType_WhenNoQueryParamProvided()
2026-08-03T04:29:42.8159766Z [xUnit.net 00:00:05.87]         --- End of stack trace from previous location ---

Copilot AI review requested due to automatic review settings August 5, 2026 10:29

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR addresses minimal API validation for nullable parameters so that validation attributes are still evaluated even when the bound argument is null (e.g., no query value supplied), and adds regression coverage for the affected scenarios.

Changes:

  • Added unit tests covering validation behavior for nullable value-type parameters with [Required], [Range], and a custom ValidationAttribute.
  • Added a regression test ensuring validation/filtering behavior is consistent when parameters are omitted vs. explicitly provided.

@surya3655

Copy link
Copy Markdown
Contributor Author

@Youssef1313, I tested the Minimal API null value validation with the latest source code, and I can confirm that the issue has been resolved. I also verified that there were no existing test cases covering this null value validation scenario.

Therefore, I added new test cases for this validation, and all of them passed successfully in CI.

Could you please review the test cases and share your feedback?

@Youssef1313 Youssef1313 changed the title Fix validation for null nullable parameters in minimal APIs Add tests for validating null values of minimal API parameters Aug 6, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

Suppressed comments (4)

src/Http/Http.Extensions/test/ValidationFilterEndpointFactoryTests.cs:361

  • This theory uses null values in [InlineData] for both queryString and expectedError, but both parameters are declared non-nullable string. Update these to nullable to avoid nullability warnings under #nullable enable.
    public async Task ValidatesCustomAttributeOnNullableQueryParameter(
        string queryString,
        int expectedStatusCode,
        bool expectedHandlerExecuted,
        string expectedError)

src/Http/Http.Extensions/test/ValidationFilterEndpointFactoryTests.cs:521

  • expectedMessage defaults to null, but is declared as non-nullable string. This can trigger CS8625 under nullable. Make it string? since null is an allowed value (used to mean "don't assert on message").
    private static async Task AssertSingleValidationErrorAsync(MemoryStream body, string expectedKey, string expectedMessage = null)

src/Http/Http.Extensions/test/ValidationFilterEndpointFactoryTests.cs:332

  • The test passes null via [InlineData(null, ...)], but the parameter is declared as non-nullable string. With nullable enabled this will produce warnings (and may fail the build if warnings are treated as errors). Make the test parameter nullable to match the data.

This issue also appears in the following locations of the same file:

  • line 357
  • line 521
    public async Task ValidatesRequiredNullableQueryParameter(string queryString, int expectedStatusCode, bool expectedHandlerExecuted)

src/Http/Http.Extensions/test/ValidationFilterEndpointFactoryTests.cs:560

  • ValidationAttribute.IsValid is nullable-aware (object? input, ValidationResult? output). The current override uses non-nullable types but returns ValidationResult.Success (which is null), which can produce nullability warnings and misrepresents the contract. Align the override signature (and include the member name like the other local attribute) to keep the test deterministic.
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
            => value is 1
                ? ValidationResult.Success
                : new ValidationResult($"Value must equal 1, but was {value?.ToString() ?? "null"}.");
    }

@Youssef1313
Youssef1313 merged commit a81552c into dotnet:main Aug 6, 2026
27 checks passed
@Youssef1313

Copy link
Copy Markdown
Member

Thanks for the contribution @surya3655 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-minimal Includes minimal APIs, endpoint filters, parameter binding, request delegate generator etc community-contribution Indicates that the PR has been added by a community member feature-validation Issues related to model validation in minimal and controller-based APIs pr: pending author input For automation. Specifically separate from Needs: Author Feedback

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Validation attributes are ignored for nullable value types when passing a null value

3 participants