ASP.NET Core 6/Web Servisleri/Minimal API'yi Kullanarak Web Servis Oluşturma
Bu bölümde minimal API'yi kullanarak web servis oluşturacağız. Şimdi projenizin Program.cs dosyasını şöyle değiştirin:
using Microsoft.EntityFrameworkCore;
using WebApp.Models;
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DataContext>(opts => {
opts.UseSqlServer(builder.Configuration["ConnectionStrings:ProductConnection"]);
opts.EnableSensitiveDataLogging(true);
});
var app = builder.Build();
const string BASEURL = "api/products";
app.MapGet($"{BASEURL}/{{id}}", async (HttpContext context, DataContext data) => {
string id = context.Request.RouteValues["id"] as string;
if (id != null)
{
Product p = data.Products.Find(long.Parse(id));
if (p == null)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
}
else
{
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonSerializer.Serialize<Product>(p));
}
}
});
app.MapGet(BASEURL, async (HttpContext context, DataContext data) => {
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(JsonSerializer.Serialize<IEnumerable<Product>>(data.Products));
});
app.MapPost(BASEURL, async (HttpContext context, DataContext data) => {
Product p = await JsonSerializer.DeserializeAsync<Product>(context.Request.Body);
if (p != null)
{
await data.AddAsync(p);
await data.SaveChangesAsync();
context.Response.StatusCode = StatusCodes.Status200OK;
}
});
app.MapGet("/", () => "Hello World!");
var context = app.Services.CreateScope().ServiceProvider.GetRequiredService<DataContext>();
SeedData.SeedDatabase(context);
app.Run();
Aslında burada bilmediğimiz bir şey kullanmadık. Programımızda üç farklı rota var. Bunlar GET metoduyla yapılan "api/products/<id>", GET metoduyla yapılan "api/products" ve POST metoduyla yapılan "api/products" isteğine karşılık veriyor. İlk rotada ilgili id'ye sahip kayıt veritabanından çekilerek JSON olarak istemciye gönderiliyor, ikinci rotadan veritabanındaki bütün ürünler çekilerek istemciye gönderiliyor, üçüncü rotada request'in body'sinde bulunan JSON verisi deserialize edilerek Product nesnesine dönüştürülüp veritabanına yazılıyor.
İlk iki rotayı test etmek kolaydır. Yalnızca tarayıcı üzerinden ilgili path'a talep yapmak yeterlidir. Üçüncü rotayı test etmek için suncuya bir POST isteği göndermek için Geliştirici PowerShell pencereciğinde aşağıdaki komutu verebilirisniz:
Invoke-RestMethod http://localhost:5000/api/products -Method POST -Body (@{Name="Swimming Goggles"; Price=12.75; CategoryId=1; SupplierId=1} | ConvertTo-Json) -ContentType "application/json"
Burada özellikleri verilen Product nesnesini JSON'a çevirerek POST metoduyla sunucunun "api/products" path'ına gönderiyoruz. Şimdi tarayıcı üzerinden sunucuya http://localhost:5000/api/products talebini tekrar gönderin ve az önceki komutla eklediğiniz nesnenin veritabanına eklendiğini görün.