.NET 8 Core ile Web API Geliştirme Rehberi

image

27 Jun 2024

Bu rehberde, .NET 8 Core kullanarak bir web API oluşturmayı detaylı bir şekilde inceleyeceğiz. Proje oluşturma, gereksinimler, Entity Framework, JWT authentication ve CRUD işlemleri adım adım anlatılacaktır.

İçindekiler

  1. Proje Kurulumu ve Gereksinimler
  2. Model ve Migration Oluşturma
  3. Entity Framework Entegrasyonu
  4. Controller ve DTO'lar
  5. CRUD İşlemleri (GET, POST, PUT, DELETE)
  6. JWT Authentication

Proje Kurulumu ve Gereksinimler

1. .NET SDK ve Visual Studio Kurulumu

.NET 8 SDK'yı ve Visual Studio 2022'yi indirin ve kurun. Visual Studio'nun Community Edition'ı ücretsizdir ve API geliştirme için yeterlidir.

2. Yeni Bir Proje Oluşturma

Visual Studio'yu açın ve "Create a new project" seçeneğini seçin. Ardından "ASP.NET Core Web API" şablonunu seçin ve proje ismini belirleyin.

dotnet new webapi -n MyWebApi
cd MyWebApi

Model ve Migration Oluşturma

1. Entity Framework Core Kurulumu

Entity Framework Core, veritabanı işlemlerini yönetmek için kullanılan bir ORM (Object-Relational Mapper) aracıdır. Projeye eklemek için NuGet paket yöneticisini kullanarak aşağıdaki komutları çalıştırın:

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

2. Model Oluşturma

Models klasörü oluşturun ve içinde Product adında bir sınıf oluşturun.

namespace MyWebApi.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

3. DbContext Sınıfı Oluşturma

Data klasörü altında AppDbContext sınıfını oluşturun.

using Microsoft.EntityFrameworkCore;
using MyWebApi.Models;

namespace MyWebApi.Data
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
        public DbSet<Product> Products { get; set; }
    }
}

4. Connection String Ekleme

appsettings.json dosyasına veritabanı bağlantı stringini ekleyin.

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyWebApiDb;Trusted_Connection=True;"
}

Program.cs dosyasını güncelleyerek veritabanı bağlantısını yapılandırın.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// Add services to the container.

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

5. Migration Oluşturma ve Veritabanını Güncelleme

dotnet ef migrations add InitialCreate
dotnet ef database update

Controller ve DTO'lar

1. DTO Sınıfları

DTOs klasörü oluşturun ve ProductDto sınıfını ekleyin.

namespace MyWebApi.DTOs
{
    public class ProductDto
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
    }
}

2. ProductController Oluşturma

Controllers klasöründe ProductController sınıfını ekleyin.

using Microsoft.AspNetCore.Mvc;
using MyWebApi.Data;
using MyWebApi.DTOs;
using MyWebApi.Models;

namespace MyWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProductController : ControllerBase
    {
        private readonly AppDbContext _context;

        public ProductController(AppDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts()
        {
            return await _context.Products
                .Select(p => new ProductDto { Id = p.Id, Name = p.Name, Price = p.Price })
                .ToListAsync();
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<ProductDto>> GetProduct(int id)
        {
            var product = await _context.Products.FindAsync(id);
            if (product == null)
            {
                return NotFound();
            }

            return new ProductDto { Id = product.Id, Name = product.Name, Price = product.Price };
        }

        [HttpPost]
        public async Task<ActionResult<ProductDto>> CreateProduct(ProductDto productDto)
        {
            var product = new Product { Name = productDto.Name, Price = productDto.Price };
            _context.Products.Add(product);
            await _context.SaveChangesAsync();

            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, new ProductDto { Id = product.Id, Name = product.Name, Price = product.Price });
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateProduct(int id, ProductDto productDto)
        {
            if (id != productDto.Id)
            {
                return BadRequest();
            }

            var product = await _context.Products.FindAsync(id);
            if (product == null)
            {
                return NotFound();
            }

            product.Name = productDto.Name;
            product.Price = productDto.Price;

            await _context.SaveChangesAsync();

            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteProduct(int id)
        {
            var product = await _context.Products.FindAsync(id);
            if (product == null)
            {
                return NotFound();
            }

            _context.Products.Remove(product);
            await _context.SaveChangesAsync();

            return NoContent();
        }
    }
}

JWT Authentication

1. JWT Paketlerinin Eklenmesi

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package System.IdentityModel.Tokens.Jwt

2. Authentication ve Authorization Middleware Eklenmesi

Program.cs dosyasını güncelleyin:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = builder.Configuration["Jwt:Issuer"],
            ValidAudience = builder.Configuration["Jwt:Audience"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]))
        };
    });

builder.Services.AddAuthorization();

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllers();

app.Run();

3. JWT Ayarlarının Eklenmesi

appsettings.json dosyasına JWT ayarlarını ekleyin:

"Jwt": {
  "Key": "your_secret_key_here",
  "Issuer": "your_issuer_here",
  "Audience": "your_audience_here",
  "ExpireMinutes": 60
}

4. JWT Üretimi İçin Controller

AuthController sınıfını oluşturun:

using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace MyWebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        private readonly IConfiguration _configuration;

        public AuthController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpPost("login")]
        public IActionResult Login([FromBody] UserLoginDto userLogin)
        {
            // This is just for demo purposes, replace with real user validation
            if (userLogin.Username == "test" && userLogin.Password == "password")
            {
                var token = GenerateJwtToken(userLogin.Username);
                return Ok(new { token });
            }

            return Unauthorized();
        }

        private string GenerateJwtToken(string username)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, username),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var token = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(Convert.ToDouble(_configuration["Jwt:ExpireMinutes"])),
                signingCredentials: credentials);

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }

    public class UserLoginDto
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }
}

Sonuç

Bu rehberde, .NET 8 Core kullanarak bir web API oluşturmayı adım adım inceledik. Proje kurulumundan, modeller ve migration'lar oluşturmaya, CRUD işlemlerine ve JWT authentication'a kadar tüm adımları detaylı bir şekilde ele aldık. Bu adımları takip ederek kendi web API'nizi oluşturabilir ve geliştirebilirsiniz.