Menu
CoddyTech

Conflitti

Fa parte della sezione API REST del percorso ASP.NET Core di Coddy. Lezione 9 di 20.

Un secondo utente chiamato "Ada" rende gli accessi ambigui, ma il corpo è valido. Questo è un 409 Conflict: la richiesta è in conflitto con ciò che è già memorizzato. Un 400 significa che il corpo stesso è errato; un 409 significa che va bene, ma non può essere applicato in questo momento.

bool NameTaken(string name, int exceptId) =>
    users.Any(u => u.Id != exceptId &&
        string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));

if (NameTaken(input.Name, id))
    return Results.Problem(title: "That name is taken.", statusCode: 409);

Le persone leggono "Ada" e "ada" come lo stesso nome, quindi confronta con StringComparison.OrdinalIgnoreCase. Quando una richiesta rinomina un utente, escludi quell'utente dalla ricerca: altrimenti, salvare un modulo senza modificare il nome genera un conflitto con sé stesso. Results.Problem restituisce una risposta nel formato dei dettagli del problema, con il titolo e lo stato specificati.

challenge icon

Sfida

Medio

Due attività chiamate "Send the invoice" rendono confuso l'elenco. Rifiuta un titolo che un'altra attività ha già.

  1. In Program.cs, sotto nextId, scrivi una funzione locale bool TitleTaken(string title, int exceptId): restituisce true quando un'attività diversa da exceptId ha quel titolo, ignorando maiuscole e minuscole.
  2. In POST, dopo il controllo di convalida, restituisci Results.Problem(title: "A task with this title already exists.", statusCode: 409) quando il titolo è già presente e non aggiungere nulla. POST non ha un'attività da escludere, quindi passa 0.
  3. Fai lo stesso in PUT, passando l'id dell'attività, così un'attività può mantenere il proprio titolo o cambiarne le maiuscole.
  4. In PATCH, controlla solo quando il corpo della richiesta invia un titolo (patch.Title non è null).

Una richiesta rifiutata non modifica nulla. Il corpo della risposta 409 è:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.10", "title": "A task with this title already exists.", "status": 409, "traceId": "..." }

Prova: premi Esegui e invia con POST { "title": "book the MEETING room" } a /api/tasks: 409, perché l'attività 2 ha quel titolo. Invia con PUT { "title": "Book the Meeting Room", "done": false } a /api/tasks/2: 200, è il titolo della stessa attività. Invia con PATCH a /api/tasks/3 { "title": "Write the project brief" }: 409. Invia con POST { "title": "Order new chairs" }: 201 con id 4.

Provalo tu

using System.ComponentModel.DataAnnotations;

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

app.UseExceptionHandler();
app.UseStatusCodePages();

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) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    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) =>
{
    var errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    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(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);

Tutte le lezioni di API REST