How to transform a response using an ITransformProvider
See original GitHub issueI want to completely rewrite the body of a response - how can this be done?
The AddResponseTransform section of the docs mentions the AddResponseTransform method which:
allows creating a custom response transform without implementing a ResponseTransform derived class
The ResponseTransform section of the docs mentions:
Avoid reading or modifying the response body as this may disrupt the proxying flow
So how are we meant to transform the response body? It seems like the docs are saying “you can mody the response but not the response body” - is that the case?
I’ve tried the following, which results in the modified body being included in the response followed by the original response;
public class MyTransformProvider : ITransformProvider
{
public void Apply(TransformBuilderContext context)
{
var transform = new ResponseFuncTransform((context) =>
{
var responseObject = new
{
Value = "Transformed Response"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(responseObject);
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
context.HttpContext.Response.Body.WriteAsync(bytes, 0, bytes.Length);
return new ValueTask(Task.FromResult(responseObject));
});
context.ResponseTransforms.Add(transform);
}
// ...
}
Returns a response body of:
{
"Value":"Transformed Response"
}{
"Value":"Original response returned by server"
}
Any help understanding how to completely transform a response, including the response content/body, would be greatly appreciated. I’m finding the online documentation and inline code documentation a little light when it comes to transformations.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:10 (6 by maintainers)
Top Related StackOverflow Question
The
ResponseTransformContexthas aSuppressResponseBodyflag you can set if you don’t want YARP to copy it for you.Also note that the
ResponseFuncTransformisn’t expecting a result, so there is no need to return the response object. You do have to await async actions you perform as part of the callback though (WriteAsync)Re-opening this to add some doc guidance. We don’t have coverage for SuppressResponseBody, nor about clearing/replacing response headers.