3

I am using Ocelot and API gateway with Consul and the service discovery. I am registering services in the Consul with dynamic names like : service.name.1234 and service.name.5678

This services are statful and not meant to be scaled at all

Since i am working with Ocelot i would like to be able to route a request to the desired service but since the names are dynamic i would need to use the query string parameter as the service name

Example : http://myapp.com/service/1234 Should be redirected to the container with the name service.name.1234

Is there any way to achive this using both products? or maybe other product?

Thank you

IB.
  • 1,019
  • 3
  • 13
  • 21

1 Answers1

0

I have been searching for myself for the same solution but found only one comment on GitHub and it helped me a lot

So, you need to create custom middleware that will rewrite Ocelot`s DownstreamRoute:

public static async Task InvokeAsync(HttpContext httpContext, Func<Task> next)
    {
        
        var downstreamRoute = httpContext.Items.DownstreamRoute();

        var yourServiceName = //get query string parameter from httpContext;

        //rewrite any parameter that you want
        httpContext.Items.UpsertDownstreamRoute(
            new DownstreamRoute(
                downstreamRoute.Key,
                downstreamRoute.UpstreamPathTemplate,
                downstreamRoute.UpstreamHeadersFindAndReplace,
                downstreamRoute.DownstreamHeadersFindAndReplace,
                downstreamRoute.DownstreamAddresses,
                tenantServiceName,
                ...
            ));
    }

And after that call it in Startup.cs:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // some other code

    var configuration = new OcelotPipelineConfiguration
            {
                PreQueryStringBuilderMiddleware = async (ctx, next) =>
                {
                    await RouteContextRetrieverMiddleware.InvokeAsync(ctx, next);

                    await next.Invoke();
                }
            };

            app.UseOcelot(configuration).GetAwaiter().GetResult();
}
Lastivez
  • 67
  • 1
  • 4
  • This works only for the first time for me as when I tried to switch it again to a new tenant, the downstream host did not change and continued to be the old tenant – Praveen Valavan Jun 28 '23 at 10:22