Home > Net >  How to create a delegate with dynamically generated properties?
How to create a delegate with dynamically generated properties?

Time:12-11

I try to create API endpoints dynamically. However the query I use to construct the endpoint can contain variables that need to be set in the API call. The parameters need to be set one by one in order to construct the correct API method. How can I create a delegate with a unknown list of named properties?

The below code tries to demonstrate what I would like to achieve:

// command.Query = "http://..../{{value1}}/query?amount={{amount}}"
var matches = Regex.Matches(command.Query, @"{{[\w|\d] }}");

app.MapGet(command.Endpoint, async (ApiService service, matches[0].Name, matches[1].Name, ...) 
    => await service.ExecuteApiCallRegex(command.Query, matches[0].Name, matches[1].Name, ...))
   .WithSummary(command.Description)
   .WithOpenApi();

public async Task<IResult> ExecuteApiCallRegex(string uri, params string[] parameters) { ... }

enter image description here

CodePudding user response:

I resolved my issue by modifying WithOpenApi. And accessing the values via HttpRequest inside the method.

app.MapGet(command.Endpoint, async (ApiService service, HttpRequest request) => await service.ExecuteApiCallRegex(command.Query, request))
    .WithSummary(command.Description)
    .WithOpenApi(operation =>
    {
        var matches = Regex.Matches(command.Query, @"{{[\w|\d] }}");
        foreach (var match in matches.AsEnumerable())
        {
            var name = match.Value.Substring(2, match.Value.Length - 4);
            if (operation.Parameters.Any(_ => _.Name == name))
            {
                continue;
            }
    
            operation.Parameters.Add(new OpenApiParameter
            {
                Name = name,
                In = ParameterLocation.Query,
                Required = true,
                Schema = new OpenApiSchema
                {
                    Type = "string"
                }
            });
        }
    
        return operation;
    });
  • Related