【发布时间】:2021-01-30 19:35:37
【问题描述】:
在问这个问题之前我已经搜索了很多,但我发现的都是与其他主题相关的,比如在 swagger doc 中排序路径。
我可以通过这个简单的例子来说明我的问题:
abstract class Animal
{
[Required]
public string Name { get; set; }
}
class Dog : Animal
{
[Required]
public bool CanBark { get; set; }
public Color DogColor { get; set; }
}
但在我生成的 Swagger API 文档中,参数按以下顺序出现:
- CanBark(必填)
- 狗颜色
- 姓名(必填)
基本上,我想更改它们在生成的文档中出现的顺序。所以,为了做到这一点,我在 SwashBuckleConfig.cs
中创建了一个类 internal class SortBodyParams : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
var properties = schemaRegistry.Definitions.Values;
foreach (var prop in properties) // Maybe something like this
{
// Order params by Required type and by name
// This code doesn't change anything,
// although I thought it would help to order params by name
prop.properties
.OrderBy(x => x.Key)
.ToList()
.ToDictionary(x => x.Key, y => y.Value);
}
}
}
并从Register方法调用类:
public static void Register(HttpConfiguration config)
{
config
.EnableSwagger(sdc =>
{
...
sdc.DocumentFilter<SortBodyParams>();
...
}
}
有人可以帮我先订购所需的参数并按名称订购吗?
【问题讨论】:
-
上述 sn-p 的一个问题是您丢弃了排序和字典转换的结果。你必须做 prop.properties = ....
-
@arynaq 你是对的,但我仍然必须订购我所需的参数,所以我认为下面的答案是最好的
标签: c# api swagger swashbuckle