Files
Backend-Api/ServiceHost/MiddleWare/RazorJsonEnumOverrideMiddleware.cs
2025-07-13 14:17:52 +03:30

65 lines
2.1 KiB
C#

using System.Text.Json;
using System.Text;
namespace ServiceHost.MiddleWare;
public class RazorJsonEnumOverrideMiddleware
{
private readonly RequestDelegate _next;
public RazorJsonEnumOverrideMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
var originalBody = context.Response.Body;
using var newBody = new MemoryStream();
context.Response.Body = newBody;
try
{
await _next(context);
if (!context.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase) &&
context.Response.ContentType?.Contains("application/json", StringComparison.OrdinalIgnoreCase) == true)
{
newBody.Seek(0, SeekOrigin.Begin);
var originalJson = await new StreamReader(newBody).ReadToEndAsync();
try
{
var obj = JsonSerializer.Deserialize<object>(originalJson);
var newJson = JsonSerializer.Serialize(obj, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
context.Response.Body = originalBody;
context.Response.ContentLength = Encoding.UTF8.GetByteCount(newJson);
if (!context.Response.HasStarted)
await context.Response.WriteAsync(newJson);
return;
}
catch
{
context.Response.Body = originalBody;
newBody.Seek(0, SeekOrigin.Begin);
if (!context.Response.HasStarted)
await newBody.CopyToAsync(originalBody);
return;
}
}
context.Response.Body = originalBody;
newBody.Seek(0, SeekOrigin.Begin);
if (!context.Response.HasStarted)
await newBody.CopyToAsync(originalBody);
}
finally
{
context.Response.Body = originalBody;
}
}
}