検証属性
CoddyのASP.NET Coreジャーニー「REST API」セクションの一部。レッスン 7/20。
すべてのルールをifとして書くと長くなります。データ注釈を使うと、System.ComponentModel.DataAnnotationsの属性として型にルールを設定でき、Validatorがオブジェクトをそれらのルールに照らして検証します。
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);位置指定レコードでは、property:を使うと属性がプロパティに設定されます。Validatorが確認するのはこのプロパティです。validateAllProperties: trueがない場合、[Required]だけを確認します。ルールに違反するたびに、プロパティ名とメッセージを含むValidationResultが追加されます。.NET 10には、エンドポイントのパラメーターを自動で確認するbuilder.Services.AddValidation()もありますが、独自の型で使うにはソースジェネレーターが必要です。ここで使うランナーはソースジェネレーターを実行しないため、自分でValidatorを呼び出します。
チャレンジ
中級タイトルのルールをTaskInputに移し、新しいルールを追加します。タイトルは最大80文字です。
Validation.csという新しいファイルがあります。そのErrorsメソッドは、Results.ValidationProblemが受け取る辞書に結果を変換します。コメントのある場所に、Validator.TryValidateObjectを使ってmodelを検証します。その際、新しいValidationContext(model)、results、およびvalidateAllProperties: trueを渡します。Program.csの先頭にusing System.ComponentModel.DataAnnotations;を追加し、TaskInputのTitleに2つの属性を付けます。[property: Required(ErrorMessage = "Title is required."), StringLength(80)]。- POSTとPUTで、
IsNullOrWhiteSpaceのチェックをvar errors = Validation.Errors(input);に置き換え、nullでない場合はResults.ValidationProblem(errors)を返します。
タイトルが81文字の場合、次の内容とともに400を返すようになります。
"errors": { "title": ["The field Title must be a string with a maximum length of 80."] }試してみましょう:「実行」を押し、タイトルが81文字の本文を/api/tasksにPOSTします。400と上記のエラーが返されます。{ "title": "" }をPOSTすると、以前と同様にTitle is required.とともに400が返されます。{ "title": "Order new chairs" }をPOSTすると、201が返されます。
自分で試してみよう
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);