3

I have an application that uses a .NET 6 Web API. Once a user logs into the application, small context based information regarding that user is appended to the query parameter.

Part of the AuthPolicy in the API is that these query parameters must be present when calling the endpoint, even if they're not being used by that endpoint.

For example, this SaveClient endpoint has the actual inputs passed in the request body, but the AuthPolicy requires the query parameter to be present even though it's not used.

Valid EX: SaveClient?clientId=1

Invalid EX: SaveClient

Is there a way I can have Swagger hardcode the query parameters to it's request URL?

1 Answer 1

3

I figured out that you can extend IOperationFilter and it's Apply method to add parameters to every endpoint.

public class ClientFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context) 
    {
        if (operation.Parameters is null)
        {
             operation.Parameters = new List<OpenApiParameter>();
        }

        if (!operation.Parameters.Any(x => x.Name.Equals("clientId", StringComparison.OrdinalIgnoreCase)))
        {
             operation.Parameters.Add(new OpenApiParameter()
             {
                 Name = "clientId"
                 In = ParameterLocation.Query,
                 Description = "ClientId Parameter",
                 Required = true,
             };
        }
    }
}

From here, you can add this OperationFilter in the Startup.cs:

services.AddSwaggerGen(c =>
{
    c.OperationFilter<ClientFilter>();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.