Can't create a body in the transform if the original request doesn't contain one
Describe the bug
In v2.2.0 we had following code of custom transform
public override async Task ApplyRequestTransform(RequestTransformContext requestContext)
{
requestContext.ProxyRequest.Content = new StringContent(body, Encoding.UTF8, contentType);
}
After upgrade to v2.3.0, we can't use this code anymore due to new exception that is being thrown (See #2722).
I'm trying following logic to make it work, but no luck. Downstream service receives empty body.
var bodyBytes = Encoding.UTF8.GetBytes(body);
requestContext.HttpContext.Request.Body = new MemoryStream(bodyBytes);
requestContext.HttpContext.Request.Headers.ContentLength = bodyBytes.Length;
requestContext.ProxyRequest.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
I am not able to find a workaround for this :(
To Reproduce
Just transform GET request to POST with body
- Make a request transform that converts
GETrequest toPOSTsetting new body. - Downstream service will receive empty body.
Further technical details
- Yarp 2.3.0
See https://learn.microsoft.com/aspnet/core/fundamentals/servers/yarp/extensibility-transforms?view=aspnetcore-9.0#:~:text=Custom%20transforms%20can%20only%20modify%20a%20request%20body%20if%20one%20is%20already%20present. The doc was recently improved to call out that request transforms can't create a body if one didn't exist previously with the default body detection logic - see the sample for how that can be overridden.
Thanks for the quick reply (as always)!
Is there any chance this could be improved in a future version, so we can use it without writing custom middleware?
For example, maybe some built-in middleware could detect all routes that use some BodyTransform transformer to automatically apply needed logic to make it work?
We've seen this come up a few times https://github.com/dotnet/yarp/issues/2617#issuecomment-2381343325, #2086, #2809, so I'd be inclined to say that we should consider making this work out of the box.