简体   繁体   中英

How to add query parameters to every Swagger request?

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?

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

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