पाठ 12 / 26

Routing और Model Binding

Route values, query strings और JSON bodies पढ़ें और सही status codes लौटाएँ।

Values कहाँ से आती हैं

Handler के parameters अपने आप bind होते हैं: {braces} वाले नाम route से, सरल types query string से, और जटिल type JSON body से आते हैं। Results.* helpers status code तय करते हैं।

id से GET और POST

TypedResults.NotFound() 404 देता है और TypedResults.Created Location header के साथ 201 देता है।

var products = new List<Product>();

app.MapGet("/products/{id:int}", (int id) =>
    products.FirstOrDefault(p => p.Id == id) is { } p
        ? Results.Ok(p)
        : Results.NotFound());

app.MapPost("/products", (Product p) =>
{
    products.Add(p);
    return Results.Created($"/products/{p.Id}", p);
});

record Product(int Id, string Name);

Route constraints लगाएँ

{id:int} से /products/abc match ही नहीं होता, तो handler में conversion error की जगह 404 मिलता है। संबंधित routes को app.MapGroup("/products") से समूहित करें।

त्वरित जाँच: संसाधन बनाने वाली सफल POST को कौन-सा status code लौटाना चाहिए?

  • सिर्फ़ 200 OK
  • 204 No Content
  • 404 Not Found
  • 201 Created
Answer

201 Created — 201 बताता है कि नया संसाधन बन गया है, आदर्श रूप से उसकी ओर इशारा करते Location header के साथ।