pushed api files

pushed middlewares
This commit is contained in:
ElenitaMLG
2024-04-07 02:49:34 +03:00
parent 55eaa0d53a
commit 2ccec617a5
11 changed files with 390 additions and 54 deletions
@@ -0,0 +1,35 @@
using System.Net;
using System.Text;
namespace API.Middlewares;
public class BodyCheckMiddleware(RequestDelegate next)
{
private readonly RequestDelegate _next = next;
public async Task InvokeAsync(HttpContext context)
{
// Only check the body for POST and PUT requests
if (context.Request.Method == HttpMethods.Post || context.Request.Method == HttpMethods.Put)
{
// Enable buffering so we can read the stream without issues downstream
context.Request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(context.Request.ContentLength)];
await context.Request.Body.ReadAsync(buffer, 0, buffer.Length);
string requestBody = Encoding.UTF8.GetString(buffer);
context.Request.Body.Seek(0, SeekOrigin.Begin); // Reset the stream for next middleware
// Check if the body is empty
if (string.IsNullOrEmpty(requestBody))
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
await context.Response.WriteAsync("Request body cannot be empty.");
return;
}
}
await _next(context);
}
}