Reputation: 347
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?
Upvotes: 3
Views: 2718
Reputation: 347
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>();
}
Upvotes: 3