Search code examples
c#odataowinswagger-uiswagger-2.0

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?


Solution

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

    class EnableQueryFiler : 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>();