.NET Core Web api için Options Pattern
NET Core’da uygulama yapılandırmasına (configuration) güçlü tip (strongly-typed) erişim sağlamanın tercih edilen yoludur. Bu desen…
.NET Core Web api için Options Pattern
NET Core’da uygulama yapılandırmasına (configuration) güçlü tip (strongly-typed) erişim sağlamanın tercih edilen yoludur. Bu desen, yapılandırma ayarlarını appsettings.json gibi dosyalardan okuyup, bunları özel sınıflara (Options classes) bağlamayı (bind) ve bu sınıfları Dependency Injection (DI) yoluyla uygulamanızın farklı yerlerinde kullanmayı sağlar. Bu, özellikle tek sorumluluk ilkesini (Single Responsibility Principle) destekler; bir sınıfın sadece ihtiyaç duyduğu ayarları bilmesini sağlar
Options Pattern ve JWT İçin Örnek.
public class JwtSettings
{
public const string SectionName = "JwtSettings";
public string Key { get; set; } = string.Empty;
public string Issuer { get; set; } = string.Empty;
public string Audience { get; set; } = string.Empty;
public int ExpiresInMinutes { get; set; } = 60;
}
{
"JwtSettings": {
"Key": "554jhsdfghjkıytredcfvghutfrfdfyghjkpljr4r567y488484-",
"Issuer": "http://localhost:5000",
"Audience": "http://localhost:5001",
"ExpiresInMinutes": 30
},
"AllowedHosts": "*"
}
Controller de kullanımı.
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]")]
public class AuthController : ControllerBase
{
private readonly JwtSettings _jwtSettings;
public AuthController(IOptions<JwtSettings> jwtOptions)
{
_jwtSettings = jwtOptions.Value;
}
[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel model)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.Key);
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _jwtSettings.Issuer,
Audience = _jwtSettings.Audience,
Expires = DateTime.UtcNow.AddMinutes(_jwtSettings.ExpiresInMinutes), // Süreyi kullanma
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(new { Token = tokenHandler.WriteToken(token) });
}
} 메타데이터
- post_id
- d21030e6da9f
- slug
- net-core-web-api-için-options-pattern-d21030e6da9f
- url
- https://medium.com/@n.colakkadioglu/net-core-web-api-i%C3%A7in-options-pattern-d21030e6da9f
- canonical_url
- https://medium.com/@n.colakkadioglu/net-core-web-api-i%C3%A7in-options-pattern-d21030e6da9f
- author_url
- https://medium.com/@n.colakkadioglu
- status
- ok
- fetched_at
- 2026-06-09 15:37:30