How to transform a POST request as GET with request body as query strings? #1457
-
Hi, I have a requirement to read the request body and transform it to query strings. The request is
I want to transform it as I tried with the following code
but get's the exception
Any guidelines or examples for this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I would suggest transforming the request body into the query before invoking the forwarder. For this to work you will also have to change the request's method to GET and clear the app.MapReverseProxy(proxyPipeline =>
{
proxyPipeline.Use(static async (context, next) =>
{
if (context.Request.Method == HttpMethods.Post)
{
var proxyFeature = context.GetReverseProxyFeature();
if (proxyFeature?.Route.Config.RouteId == "route2")
{
context.Request.Method = HttpMethods.Get;
context.Request.Headers.ContentLength = null;
var data = await context.Request.ReadFromJsonAsync<Foo>();
if (data is not null)
{
var query = context.Request.QueryString;
query = query.Add("a", data.a);
query = query.Add("b", data.b);
context.Request.QueryString = query;
}
}
}
await next();
});
proxyPipeline.UseSessionAffinity();
proxyPipeline.UseLoadBalancing();
}); |
Beta Was this translation helpful? Give feedback.
ReadFromJsonAsync
will consume the request body stream, so when YARP tries to proxy the request, there will be a mismatch between theContent-Length
header and the content actually available.I would suggest transforming the request body into the query before invoking the forwarder.
For this to work you will also have to change the request's method to GET and clear the
Content-Length
header as well.