Skip to content

Instantly share code, notes, and snippets.

@hasmukhlalpatel
Last active January 19, 2025 22:13
Show Gist options
  • Select an option

  • Save hasmukhlalpatel/d7254d94962468fd72f11069f5ad3599 to your computer and use it in GitHub Desktop.

Select an option

Save hasmukhlalpatel/d7254d94962468fd72f11069f5ad3599 to your computer and use it in GitHub Desktop.
Custom Endpoint Selector Middleware for yarp or override route/ endpoint- yarp revers proxy

In Yarp reversproxy, If there is missing endpoint or not selected or if you wanna override

app.UseMiddleware<CustomEndpointSelectorMiddleware>();
public class CustomEndpointSelectorMiddleware
{
    private readonly RequestDelegate _next;
    private readonly EndpointDataSource _endpointDataSource;

    public CustomEndpointSelectorMiddleware(RequestDelegate next, EndpointDataSource endpointDataSource)
    {
        _next = next;
        _endpointDataSource = endpointDataSource;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var endpoint = context.GetEndpoint();
        if (endpoint == null)
        {
            var endpoints = _endpointDataSource.Endpoints;
            // Select the first endpoint from the list
            //write your custom logic here
            context.SetEndpoint(endpoints[0]);
        }

        await _next(context);
    }
}

Or mutiple matches then use CustomEndpointSelector

builder.Services.AddSingleton<EndpointSelector, CustomEndpointSelector>();
public class CustomEndpointSelector : EndpointSelector
{
    public override Task SelectAsync(HttpContext httpContext, CandidateSet candidates)
    {
        for (int i = 0; i < candidates.Count; i++)
        {
            var endpoint = candidates[i].Endpoint;
            //wrtite your custom logic here
            if (endpoint.DisplayName == "SpecialEndpoint")
            {
                candidates.SetValidity(i, true);
            }
            else
            {
                candidates.SetValidity(i, false);
            }
        }

        return Task.CompletedTask;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment