Middleware Nedir?
Middleware, HTTP istek ve yanıt döngüsünde çalışan yazılım bileşenleridir. Her middleware bir sonrakini çağırabilir veya döngüyü kesebilir.
Pipeline Sıralaması
app.UseExceptionHandler("/error"); // 1. Hata yakalama
app.UseHttpsRedirection(); // 2. HTTPS yönlendirme
app.UseStaticFiles(); // 3. Statik dosyalar
app.UseRouting(); // 4. Routing
app.UseCors("Policy"); // 5. CORS
app.UseAuthentication(); // 6. Kimlik doğrulama
app.UseAuthorization(); // 7. Yetkilendirme
app.MapControllers(); // 8. Controller'larÖzel Middleware
public class IslemSuresiMiddleware {
private readonly RequestDelegate _sonraki;
private readonly ILogger _logger;
public IslemSuresiMiddleware(RequestDelegate sonraki, ILogger<IslemSuresiMiddleware> logger) {
_sonraki = sonraki;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context) {
var sw = Stopwatch.StartNew();
await _sonraki(context);
sw.Stop();
_logger.LogInformation("{Method} {Path} — {Ms}ms",
context.Request.Method, context.Request.Path, sw.ElapsedMilliseconds);
}
}
// Kayıt
app.UseMiddleware<IslemSuresiMiddleware>();