teca
teca

Reputation: 1

"The request cannot be forwarded, the response has already started" error in YARP

I get a 504 message back when I make a request through a YARP server. Apparently this is a timing issue between the backend and the YARP server. The backend server responds normally when I address it directly with this request through the browser without a proxy. I have added middleware. If the HTTP status of the response of the backend server is 504, the same request should be sent again. I use the the BasicYARPSample(https://github.com/microsoft/reverse-proxy/tree/release/latest/samples/BasicYarpSample)+ code for the middleware.

My code doesn't work. The command "await next();" in the if-clause throws an exception. I get the following error message:" An unhandled exception has occurred while executing the request. System.InvalidOperationException: The request cannot be forwarded, the response has already started"

Any suggestions?

app.UseEndpoints(endpoints =>
            {
                endpoints.MapReverseProxy(proxyPipeline => {
    
                    proxyPipeline.Use(async (context, next) =>
                    {
                        await next();
                    
                        if ((context.Response.StatusCode>=500) &&(context.Response.StatusCode <= 504))
                        {
                            int maxRetries = 3;
                            TimeSpan retryDelay = TimeSpan.FromSeconds(5);
                            int retries = 0;

                            while (retries < maxRetries)
                            {

                                await Task.Delay(retryDelay);
                                await next();

                                if (!((context.Response.StatusCode >= 500) && (context.Response.StatusCode <= 504)))
                                {
                                    break;
                                }

                                retries++;
                            }
                        }
                        
                    });
                        
                    proxyPipeline.UseSessionAffinity();
                    proxyPipeline.UseLoadBalancing();
                    proxyPipeline.UsePassiveHealthChecks();

                });
            });  ``` 

Upvotes: 0

Views: 2593

Answers (1)

Tratcher
Tratcher

Reputation: 6094

You cannot retry a response that has a body like this, the response has already been flushed through to the client. You would either need to enable response body buffering, or tell YARP to conditionally not forward the response. See

Upvotes: 0

Related Questions