Search code examples
c#.netreverse-proxyms-yarp

How to have middleware conditionally forward request C#, using yarp


I am registering a middleware in the Startup.cs file. In the middleware, i am forwarding the request based on a condition. However, if the condition is not met i would like the default execution flow to be processed (no request forwarding but continue with the expected flow). However, if i dont do anything when the condition is not met, nothing is returned. Here is the code

    app.UseEndpoints(endpoints =>
    {
        endpoints.Map("path/{**catch-all}", async httpContext =>
        {
            if (conditionIsMet)
            {
                var error = await forwarder.SendAsync(httpContext, endpoint), httpClient, requestOptions, transformer);

                // Check if the proxy operation was successful
                if (error != ForwarderError.None)
                {
                    var errorFeature = httpContext.Features.Get<IForwarderErrorFeature>();
                    var exception = errorFeature.Exception;
                }
            }
            else
            {
                //how do i have the default controller that is mapped to this endpoint handle the request?
            }
        });
    });

Solution

  • Use middleware to do this:

    app.Use(async (httpContext, next) =>
    {
        if (httpContext.Request.Path.StartsWithSegments("path") && conditionIsMet)
        {
            var error = await forwarder.SendAsync(httpContext, endpoint, httpClient, requestOptions, transformer);
    
            // Check if the proxy operation was successful
            if (error != ForwarderError.None)
            {
                var errorFeature = httpContext.Features.Get<IForwarderErrorFeature>();
                var exception = errorFeature.Exception;
            }
    
            return;
        }
        return next(httpContext);
    });
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });