Tamam ve Bulunamadı
Coddy'nin ASP.NET Core Journey'sinin Minimal API'ler bölümünün bir parçası. Ders 6 / 20.
Birden fazla şekilde yanıt verebilen bir uç nokta, durum kodunu belirleyen Results üzerinden bir sonuç döndürür. Results.Ok(value), değeri JSON olarak içeren 200 yanıtıdır; Results.NotFound() ise var olmayan bir şey için kullanılan 404 Not Found kodudur.
app.MapGet("/books/{id:int}", (int id) =>
{
var book = books.FirstOrDefault(b => b.Id == id);
if (book is null)
return Results.NotFound(new { error = "No such book" });
return Results.Ok(book);
});Her return, Results üzerinden geçtiğinden aynı türü, IResult türünü paylaşırlar ve lambda derlenir. new { error = "No such book" } anonim bir nesnedir: ASP.NET Core bunu {"error":"No such book"} olarak yazar; bu gövde, istemciye neyin yanlış gittiğini bildirir.
Görev
KolayGET /api/recipes/99, null ile 200 yanıtı verir. Bir istemci bunu var olan bir tariften ayırt edemez; bu nedenle yanıt 404 olmalıdır.
Program.csdosyasında,GET /api/recipes/{id:int}lambda'sına{ ... }blok gövdesi ekleyerekFirstOrDefaultile tarifi bul.- Değer
nullolduğundaResults.NotFound(new { error = $"Recipe {id} not found" })döndür. 99 kimliği için gövde{"error":"Recipe 99 not found"}olur. - Aksi takdirde
Results.Ok(recipe)döndür.
Dene: “Çalıştır” düğmesine bas. GET /api/recipes/99, durum kodu 404 ve {"error":"Recipe 99 not found"} ile yanıt verir. GET /api/recipes/2 isteğini gönder: daha önce olduğu gibi durum kodu 200 ve Pancakes tarifi.
Kendin dene
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var recipes = new List<Recipe>
{
new(1, "Tomato Soup", "soup", 25),
new(2, "Pancakes", "breakfast", 15),
new(3, "Lentil Soup", "soup", 40),
};
app.MapGet("/", () => "Recipe API is running");
app.MapGet("/api/recipes", (string? category) =>
recipes.Where(r => category is null || r.Category == category));
app.MapGet("/api/recipes/{id:int}", (int id) => recipes.FirstOrDefault(r => r.Id == id));
app.Run();
Minimal API'ler bölümündeki tüm dersler
2Sonuçlar ve JSON Gövdeleri
Tamam ve Bulunamadı