In a dotnet project i'm trying to list the possible values for a parameter to be able to just select it in dropdown.
but currently the parameter is listed as object (query) but instead it should be a string type
the code:
c.OperationFilter<SwaggerExt>();
public class SwaggerExt : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
return;
foreach (var parameter in operation.Parameters)
{
if (parameter.Name == "P1")
{
parameter.Schema = new OpenApiSchema
{
Type = "object",
Properties = new Dictionary<string, OpenApiSchema>
{
{
"P1",
new OpenApiSchema
{
Type = "string",
Enum = new List<IOpenApiAny>
{
new OpenApiString("value-1"),
new OpenApiString("value-2"),
new OpenApiString("value-3")
}
}
}
}
};
}
}
}
}
Based on @Helen comment, that was part of the issue,
so what i did to solve this problem is to change the type from an Object to an Array and then define the list inside the Items.
So in order to define an Array of String for a specific parameter in Swagger here is what i did:
I needed also to make the values dynamic from another service: there are multiple ways to achieve this, you can make a constructor and inject only the list or manage it inside the OperationFilter by injecting IYourService
public class SwaggerCustomsFilter : IOperationFilter
{
private readonly IHttpContextAccessor _contextAccessor;
public SwaggerCustomsFilter(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null)
return;
//
// Use Linq: firstOrDefault to optimize the foreach loop and check if parameter is not null
//
foreach (var parameter in operation.Parameters)
{
if (parameter.Name == "ParameterName")
{
var test = _contextAccessor.HttpContext.RequestServices.GetRequiredService<IYourService>();
var values = test.GetValues();
parameter.Schema = new OpenApiSchema
{
Type = "array",
Items = new OpenApiSchema
{
Type = "string",
Enum = new List<IOpenApiAny>(values.Select(v => new OpenApiString(v)).ToList())
}
};
}
}
}
}
Note
if your parameter is not an array try what @helen mentioned in the screenshot like this:
if (parameter.Name == "P1")
{
parameter.Schema = new OpenApiSchema
{
Type = "string",
Enum = new List<IOpenApiAny>
{
new OpenApiString("value-1"),
new OpenApiString("value-2"),
new OpenApiString("value-3")
}
};
}