/
Lexus_666
/
Pir_API
Обзор
Документация
Войти
/
Lexus_666
/
Pir_API
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Middleware/IdempotencyMiddleware.cs
52 строки
2 KB
Lexus_666
Lab 2 done
20 окт 2025, 05:24
20 окт 2025, 05:24
1680046
Код
Авторство
О чём код?
using Pir_API.Interfaces; namespace Pir_API.Middleware; public class IdempotencyMiddleware { private readonly RequestDelegate _next; public IdempotencyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context, IIdempotencyService idempotencyService) { if (context.Request.Path.StartsWithSegments("/api/internal")) { await _next(context); return; } if (context.Request.Method == "POST") { if (!context.Request.Headers.TryGetValue("Idempotency-Key", out var keyValues) || string.IsNullOrEmpty(keyValues.FirstOrDefault())) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Header must contains Idempotency-Key"); return; } if (!Guid.TryParse(keyValues.First(), out var idempotencyKey)) { context.Response.StatusCode = 400; await context.Response.WriteAsync("Idempotency-Key must be a valid GUID"); return; } if (idempotencyService.ContainsKey(idempotencyKey)) { context.Response.StatusCode = 409; await context.Response.WriteAsync("Idempotency key already in use"); return; } idempotencyService.CreateKey(idempotencyKey); context.Items["IdempotencyKey"] = idempotencyKey; } await _next(context); } }