[英]Sorting the Schemas portion of a Swagger page using Swashbuckle
在我的 Swagger 頁面上,我(大部分)能夠按照 Swashbuckle 頁面上的說明進行操作。
操作下方是“模式”部分,顯示操作使用的數據結構。 這些數據結構以任意順序出現。 我想對它們進行排序。
問題Swagger sort Schema Defintions表面上看起來像同一個問題,但在那個問題中,“排序”的含義是“將項目分類到不同的箱子”,而不是我想要的“排序列表”。
我已經制作了一個“有效”的文檔過濾器,但是當我查看我編寫的代碼時,我有點死心了。
有沒有更正確的方法來做到這一點?
編輯:具體來說,我 object 對這段代碼的看法是,它通過對字典中的條目進行排序來“工作”,這很糟糕(見這個問題)。
原來答案只是使用 SortedDictionary:
openApiDoc.Components.Schemas = new System.Collections.Generic.SortedDictionary<string, OpenApiSchema>(openApiDoc.Components.Schemas);
實際上,您在使用文檔過濾器時走在了正確的軌道上!
在 Startup.cs 中, ConfigureServices
方法:-
services.AddSwaggerGen(c =>
{
// ...
// For our document filtering needs.
c.DocumentFilter<DocumentFilter>();
});
這是文檔過濾器的實現:-
using System.Linq;
public class DocumentFilter : IDocumentFilter
{
public DocumentFilter()
{
}
// Implements IDocumentFilter.Apply().
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
if (swaggerDoc == null)
return;
// Re-order the schemas alphabetically.
swaggerDoc.Components.Schemas = swaggerDoc.Components.Schemas.OrderBy(kvp => kvp.Key, StringComparer.InvariantCulture)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
}
when I look at the code I wrote, I die a little inside
死心了——擁抱 LINQ 的榮耀,你會為你的代碼感到驕傲!
這不會改變我的最終顯示順序,但MikeBeaton 在報告 GitHub 上的排序模式問題時的建議就像一個魅力..
app.UseSwagger(c =>
{
c.PreSerializeFilters.Add((swagger, _) =>
{
if (swagger.Components != null && swagger.Components.Schemas != null)
{
var replacement = new Dictionary<string, OpenApiSchema>();
foreach (var kv in swagger.Components.Schemas.OrderBy(p => p.Key))
{
replacement.Add(kv.Key, kv.Value);
}
swagger.Components.Schemas = replacement;
}
});
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.