liveBook · Manning

Dataannotations attribute

As explained in ASP.NET Core in Action, 3e

DataAnnotations is the .NET attribute-based framework for declaring metadata and validation rules on types and their members.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Works through property-level rules and framework validation behavior, including filter setup and a simple-parameter limitation.
Examples
Uses a user-details model with required names, email and phone formats, a display name, and an optional phone number.
What it assumes
Introduces validation from user-provided request data while using C# types, properties, and ASP.NET Core binding models in examples.
What you can do after
Apply it via DataAnnotations attributes on binding models and arrange server-side handling appropriate to the ASP.NET Core framework.
How it connects
Connects model binding and server-side validation with endpoint filters, IValidatableObject, FluentValidation, and EF Core.

Also explained in

Compare how 2 books explain dataannotations attribute →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.