How to transform a response using an ITransformProvider

See original GitHub issue

I 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:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:10 (6 by maintainers)

github_iconTop GitHub Comments

3reactions
MihaZupancommented, Aug 26, 2021

The ResponseTransformContext has a SuppressResponseBody flag you can set if you don’t want YARP to copy it for you.

Also note that the ResponseFuncTransform isn’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)

public void Apply(TransformBuilderContext context)
{
    var transform = new ResponseFuncTransform(async context =>
    {
        var someCondition = new Random().Next() % 2 == 1;

        if (someCondition)
        {
            context.SuppressResponseBody = true;

            await context.HttpContext.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("Hello world"));
        }
    });

    context.ResponseTransforms.Add(transform);
}
2reactions
Tratchercommented, Jan 4, 2022

Re-opening this to add some doc guidance. We don’t have coverage for SuppressResponseBody, nor about clearing/replacing response headers.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Request and Response Transforms
Transforms and can be bound from the Routes sections of the config file. These can be modified and reloaded without restarting the proxy....
Read more >
"Short-circuit" YARP RequestTransform if condition is not ...
I am having issues figuring out how to stop a YARP request early and return a custom response if a certain condition is...
Read more >
Interface ITransformProvider
Apply(TransformBuilderContext). Inspect the given route and conditionally add transforms. This is called for every route, each time that route is built.
Read more >
Micro Frontends in Action With ASP.NET Core
This post describes implementation of server-side composition via SSI sample from Micro Frontends in Action with ASP.NET Core and YARP.
Read more >
Response Transformer - Kong Docs
Transform the response sent by the upstream server on the fly before returning the response to the client. For additional response transformation features, ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found