Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OData query in swagger ui

I was checking out the following tutorial: http://blogs.msdn.com/b/martinkearn/archive/2015/03/10/using-odata-query-syntax-with-web-api.aspx

And I was curious if there was support in swagger ui somehow to show the query parameters.

Essentially I wanted all calls tagged with [EnableQueryAttribute] attribute to have swagger ui for inputting query parameters and I don't want to add these parameters to the method call I still want them to be in the URL and pulled out for the Owin context.

Any suggestions?

like image 758
nastassiar Avatar asked Oct 27 '25 14:10

nastassiar


1 Answers

The chosen answer is out of data. With .NET 5, use this instead:

class EnableQueryFilter : IOperationFilter
{
    static List<OpenApiParameter> s_Parameters = (new List<(string Name, string Description)>()
            {
                ( "$top", "The max number of records."),
                ( "$skip", "The number of records to skip."),
                ( "$filter", "A function that must evaluate to true for a record to be returned."),
                ( "$select", "Specifies a subset of properties to return. Use a comma separated list."),
                ( "$orderby", "Determines what values are used to order a collection of records."),
                ( "$expand", "Use to add related query data.")
            }).Select(pair => new OpenApiParameter
            {
                Name = pair.Name,
                Required = false,
                Schema = new OpenApiSchema { Type = "String" },
                In = ParameterLocation.Query,
                Description = pair.Description,

            }).ToList();

    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (context.ApiDescription.ActionDescriptor.EndpointMetadata.Any(em => em is Microsoft.AspNetCore.OData.Query.EnableQueryAttribute))
        {

            operation.Parameters ??= new List<OpenApiParameter>();
            foreach (var item in s_Parameters)
                operation.Parameters.Add(item);
        }
    }
}

You will then need to register the filter:

services.AddSwaggerGen(c =>
{
    c.OperationFilter<EnableQueryFilter>();
like image 160
Jonathan Allen Avatar answered Oct 29 '25 02:10

Jonathan Allen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!