Menu
CoddyTech

Validierungsattribute

Teil des Abschnitts REST-APIs der ASP.NET Core-Journey von Coddy. Lektion 7 von 20.

Jede Regel als if zu schreiben, wird schnell lang. Datenannotationen speichern die Regeln als Attribute am Typ. Sie stammen aus System.ComponentModel.DataAnnotations, und Validator prüft ein Objekt anhand dieser Regeln.

record SignupInput(
    [property: Required, EmailAddress] string Email,
    [property: Range(13, 120)] int Age);

var results = new List<ValidationResult>();
Validator.TryValidateObject(input, new ValidationContext(input), results,
    validateAllProperties: true);

In einem Positionsdatensatz platziert property: das Attribut an der Eigenschaft, dort, wo Validator danach sucht. Ohne validateAllProperties: true prüft es nur [Required]. Jede verletzte Regel fügt ein ValidationResult mit dem Namen der Eigenschaft und einer Meldung hinzu. .NET 10 bietet außerdem builder.Services.AddValidation(), das Endpunktparameter für dich prüft. Für eigene Typen ist jedoch ein Quellcodegenerator erforderlich. Der Runner hier führt keine Quellcodegeneratoren aus, daher rufst du Validator selbst auf.

challenge icon

Aufgabe

Mittel

Verschiebe die Titelregeln auf TaskInput und füge eine neue hinzu: Ein Titel darf höchstens 80 Zeichen lang sein.

  1. Du hast eine neue Datei, Validation.cs. Ihre Errors-Methode wandelt die Ergebnisse in das Wörterbuch um, das Results.ValidationProblem erwartet. Füge an der Stelle des Kommentars einen Aufruf von Validator.TryValidateObject für model mit einem neuen ValidationContext(model), results und validateAllProperties: true ein.
  2. Füge oben in Program.cs using System.ComponentModel.DataAnnotations; hinzu und versehe Title von TaskInput mit zwei Attributen: [property: Required(ErrorMessage = "Title is required."), StringLength(80)].
  3. Ersetze in POST und PUT die Prüfung mit IsNullOrWhiteSpace durch var errors = Validation.Errors(input); und gib Results.ValidationProblem(errors) zurück, wenn der Wert nicht null ist.

Ein Titel mit 81 Zeichen ergibt jetzt den Statuscode 400 mit:

"errors": { "title": ["The field Title must be a string with a maximum length of 80."] }

Probiere es aus: Drücke auf „Ausführen“ und sende per POST einen Body mit einem 81 Buchstaben langen Titel an /api/tasks: Statuscode 400 und der obige Fehler. Sende per POST { "title": "" }: Statuscode 400 mit Title is required., wie zuvor. Sende per POST { "title": "Order new chairs" }: Statuscode 201.

Probier es selbst

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

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};
var nextId = 4;

app.MapGet("/api/tasks", () => tasks);

app.MapGet("/api/tasks/{id:int}", (int id) =>
{
    var task = tasks.Find(t => t.Id == id);
    return task is null ? Results.NotFound() : Results.Ok(task);
});

app.MapPost("/api/tasks", (TaskInput input) =>
{
    if (string.IsNullOrWhiteSpace(input.Title))
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["title"] = ["Title is required."],
        });
    }
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    if (string.IsNullOrWhiteSpace(input.Title))
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["title"] = ["Title is required."],
        });
    }
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    tasks[index] = new TaskItem(id, input.Title, input.Done);
    return Results.Ok(tasks[index]);
});

app.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);
record TaskPatch(string? Title, bool? Done);

Alle Lektionen in REST-APIs