OData query in swagger ui

2019-08-12 01:01发布

问题:

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?

回答1:

The answer was much easier than I was thinking. What I ended up doing is creating an IOperationFilter and looked for all Operations with a certain return type and added the Parameters to it.

class QueryParameterFilter : IOperationFilter
    {
        void IOperationFilter.Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (apiDescription.ResponseDescription.ResponseType != null && apiDescription.ResponseDescription.ResponseType.Name.Contains("PagedResult"))
            {
                Dictionary<string, string> parameters = new Dictionary<string, string>()
                {
                    { "$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"},
                    { "$orderby", "Determines what values are used to order a collection of records"}
                };
                operation.parameters = new List<Parameter>();
                foreach (var pair in parameters)
                {
                    operation.parameters.Add(new Parameter
                    {
                        name = pair.Key,
                        required = false,
                        type = "string",
                        @in = "query",
                        description = pair.Value
                    });
                }
            }
        }

And then they can retrieved through the owin context.

var params = owinContext.Request.Query.ToDictionary(p => p.Key, p => p.Value.FirstOrDefault());