A DataAnnotations attribute declares metadata or a validation rule on a C# type or property. Put rules on a binding model to describe the user input your application expects, then validate the model before using its values. The attributes describe valid data; adding them does not, by itself, guarantee that an invalid request will be rejected. section 7.10.2 section 7.10.3
For a user-details model, common attributes express one expectation at a time:
- [Required] marks a name or email as required; leave an optional phone number without it. section 7.10.2
- [StringLength(100)] limits a name’s length, while [EmailAddress] and [Phone] check the respective formats. section 7.10.2
- [Display(Name = "Your name")] supplies a friendly property name for uses such as error messages. section 7.10.2
Listing 7.12 Adding validation to minimal APIs using MinimalApis.Extensions
using System.ComponentModel.DataAnnotations;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
app.MapPost("/users", (UserModel user) => user.ToString())
.WithParameterValidation(); #1
app.Run();
public record UserModel #2
{
[Required]
[StringLength(100)]
[Display(Name = "Your name")]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
}
#1 Adds the validation filter to the endpoint
#2 The UserModel defines its validation requirements using DataAnnotations attributes.
The /users endpoint binds JSON to UserModel. Its properties carry the rules, and WithParameterValidation() adds the filter that checks them before the handler runs. section 7.10.2 section 7.10.3
Validation behavior depends on the ASP.NET Core framework you use. Minimal APIs do not validate DataAnnotations automatically. With the shown MinimalApis.Extensions filter, invalid bound input produces a 400 Bad Request Problem Details response instead of running the handler. That filter checks attributes on a model’s properties, not an attribute placed directly on a simple handler parameter such as int id; put a range rule on a model property if you use this approach. section 7.10.3
Razor Pages and MVC use DataAnnotations-based validation automatically after model binding. In Razor Pages, the page handler still runs when validation fails, so check the validation result and handle invalid input on the server. Do not rely on client-side checks alone. section 16.3.1 section 32.4
Attributes are convenient for property-level rules, but some rules need more. Implement IValidatableObject when validity depends on multiple properties, such as requiring either an email address or a phone number. FluentValidation is an alternative that keeps rules separate from the model and can make cross-property rules easier. Also remember that EF Core does not automatically validate DataAnnotations on entities before saving them. section 7.10.2 section 32.4 section 12.5

