42 lines
1.8 KiB
C#
42 lines
1.8 KiB
C#
using Yarp.ReverseProxy.Forwarder;
|
|
|
|
namespace MP.IOC.Services
|
|
{
|
|
|
|
public class PreserveBodyTransformer : HttpTransformer
|
|
{
|
|
public override async ValueTask TransformRequestAsync(HttpContext httpContext, HttpRequestMessage proxyRequest, string destinationPrefix, CancellationToken cancellationToken)
|
|
{
|
|
// Chiama il base (usa overload con cancellationToken)
|
|
await base.TransformRequestAsync(httpContext, proxyRequest, destinationPrefix, cancellationToken);
|
|
|
|
// Imposta il method correttamente
|
|
proxyRequest.Method = new HttpMethod(httpContext.Request.Method);
|
|
|
|
// Se vuoi leggere/loggare il body, abilita buffering e rewind.
|
|
// NON assegnare proxyRequest.Content: YARP copierà il body da HttpContext.Request.
|
|
if (httpContext.Request.ContentLength > 0 || httpContext.Request.Body.CanRead)
|
|
{
|
|
// Abilita buffering solo se necessario (attenzione a payload grandi)
|
|
httpContext.Request.EnableBuffering();
|
|
|
|
// Rewind per sicurezza
|
|
httpContext.Request.Body.Position = 0;
|
|
|
|
// Se vuoi leggere il body per logging, fallo qui ma non sostituire proxyRequest.Content.
|
|
// Esempio (opzionale): leggere senza consumare
|
|
// using var sr = new StreamReader(httpContext.Request.Body, leaveOpen: true);
|
|
// var bodyText = await sr.ReadToEndAsync();
|
|
// httpContext.Request.Body.Position = 0;
|
|
}
|
|
}
|
|
|
|
public override ValueTask<bool> TransformResponseAsync(HttpContext httpContext, HttpResponseMessage? proxyResponse, CancellationToken cancellationToken)
|
|
{
|
|
return base.TransformResponseAsync(httpContext, proxyResponse, cancellationToken);
|
|
}
|
|
}
|
|
|
|
|
|
}
|