Saturday, August 30, 2025

ASP.NET Core 10.0: Validation Support for Minimal APIs

With ASP.NET Core 10.0, we now have built in validation support for Minimal APIs for request data in following.
  • Route parameters, Query Strings
  • Header
  • Request body
If any validation fails, the runtime returns a 400 Bad Request response with details of the validation errors.

Validations are defined using attributes in the System.ComponentModel.DataAnnotations namespace. We can even create our own validators using,
To register validation services and enable validation, we need to call the following method in the Program.cs.
builder.Services.AddValidation();
Now we can do something like below to validate route parameters.
app.MapGet("/employees/{employeeId}"([Range(1, int.MaxValue)] int employeeId) =>
{
    // Omitted
});
And if we try the endpoint with an incorrect route parameter, we will get an validation error.
GET {{WebApplication1_HostAddress}}/employees/0
Accept: application/json
Route parameter validation
We can use the similar concept with record types as well.

Say I have the following Employee record that has a annotated property.
internal record Employee([Required] string Name);
And now If I try to make a request to the following endpoint,
app.MapPost("/employees"(Employee employee) =>
{
    // Omitted
});
With a empty value for name,
POST {{WebApplication1_HostAddress}}/employees
Content-Type: application/json
{
    "name": ""
}
I am getting the following 400 Bad Request.
Request Body Validation
You can disable the validation at the endpoint by calling DisableValidation(), something like below:
app.MapPost("/employees"(Employee employee) =>
    {
        // Omitted
    })
    .DisableValidation();
Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment