2

I am having issues figuring out how to stop a YARP request early and return a custom response if a certain condition is not met inside a request transform.

builderContext.AddRequestTransform(async transformContext =>
{
        [...]

        if (!condition)
        {
                // TODO: stop request and return response
        }

        [...]
});

I have tried simply setting transformContext.HttpContext.Response.Status to a non-success status code as you would do for middleware, however this does not seem to work, and I have not been able to find another solution to this issue.

elillesaeter
  • 148
  • 10

2 Answers2

0

Perhaps you should use a middleware. If you take a look at the documentation, you can intercept using a middleware.

https://microsoft.github.io/reverse-proxy/articles/middleware.html#adding-middleware

if you return before next(), the proxy does not get called.

0

I handle it like that:

if (!condition){ 
    transformContext.ProxyRequest.Dispose();
    return;
    }

but there is better way and it is using middleware for example you can write your own custom validation like that:

if (transformContext.ProxyRequest.Content == null)
                {
                                       
                    throw new ArgumentException("required parameter missing or invalid");
                }

and in your program.cs set middleware config for yarp:

app.MapReverseProxy(proxyPipeline =>
            {
                proxyPipeline.Use(async (context, next) =>
                {
                    // Custom inline middleware

                    await next();
                    var errorFeature = context.GetForwarderErrorFeature();
                    if (errorFeature is not null)
                    {
                        var exType = errorFeature.Exception.GetType();

                        if (exType.Name == "ArgumentException")
                        {
                            context.Response.StatusCode = 400;
                            context.Response.ContentType = "text/plain"; // Set the content type

                            string errorMessage = errorFeature.Exception.Message; // Your custom error message
                            await context.Response.WriteAsync(errorMessage);
                            
                        }
                        else
                        {
                            
                            string errorMessage = errorFeature.Exception.Message; // Your custom error message
                            await context.Response.WriteAsync(errorMessage);
                        }

                    }

                });

            });
Ali Eshghi
  • 1,131
  • 1
  • 13
  • 30