简体   繁体   中英

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?
            }
        });
    });

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM