我正在查看以下教程:http://blogs.msdn.com/b/martinearn/archive/2015/03/10/using-odata-query-syntax-with-web-api.aspx
我很好奇 swagger ui 是否支持以某种方式显示查询参数。
本质上,我希望所有用 [EnableQueryAttribute] 属性标记的调用都具有用于输入查询参数的 swagger ui,并且我不想将这些参数添加到方法调用中,我仍然希望它们位于 URL 中并为 Owin 上下文拉出.
有什么建议吗?
所选答案没有数据。对于 .NET 5,请改用它:
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);
}
}
}
然后您需要注册过滤器:
services.AddSwaggerGen(c =>
{
c.OperationFilter<EnableQueryFilter>();
答案比我想象的要容易得多。我最终做的是创建一个 IOperationFilter 并查找具有特定返回类型的所有操作并向其中添加参数。
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
});
}
}
}
然后可以通过 owin 上下文检索它们。
var params = owinContext.Request.Query.ToDictionary(p => p.Key, p => p.Value.FirstOrDefault());
另一个解决方法是使用
[FromServices] ODataQueryOptions<OutputDto> options
然后将参数添加到控制器,例如[FromQuery] string? filter, [FromQuery] string? orderby
这些参数不会被使用,但会绑定到选项