事实证明,使用 IOperationFilter 使用 SwashBuckle 添加您想要 Swagger 的任何参数非常容易。您可以使用 c.OperationFilter<ODataParametersSwaggerDefinition>(); 将其添加到 Swagger 配置中。我创建了一个向我的 API 中的所有 IQueryable 端点添加一些 OData 参数的方法:
/// <summary>
/// Add the supported odata parameters for IQueryable endpoints.
/// </summary>
public class ODataParametersSwaggerDefinition : IOperationFilter
{
private static readonly Type QueryableType = typeof(IQueryable);
/// <summary>
/// Apply the filter to the operation.
/// </summary>
/// <param name="operation">The API operation to check.</param>
/// <param name="schemaRegistry">The swagger schema registry.</param>
/// <param name="apiDescription">The description of the api method.</param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var responseType = apiDescription.ResponseType();
if (responseType.GetInterfaces().Any(i => i == QueryableType))
{
operation.parameters.Add(new Parameter
{
name = "$filter",
description = "Filter the results using OData syntax.",
required = false,
type = "string",
@in = "query"
});
operation.parameters.Add(new Parameter
{
name = "$orderby",
description = "Order the results using OData syntax.",
required = false,
type = "string",
@in = "query"
});
operation.parameters.Add(new Parameter
{
name = "$skip",
description = "The number of results to skip.",
required = false,
type = "integer",
@in = "query"
});
operation.parameters.Add(new Parameter
{
name = "$top",
description = "The number of results to return.",
required = false,
type = "integer",
@in = "query"
});
operation.parameters.Add(new Parameter
{
name = "$count",
description = "Return the total count.",
required = false,
type = "boolean",
@in = "query"
});
}
}
}