我正在使用swagger.json文件(由Swashbuckle生成)供ReDoc显示API文档。
我需要什么:
将x-logo
供应商扩展名添加到使用Swashbuckle(Swashbuckle.AspNetCore.SwaggerGen
库)生成的swagger json中,以便ReDoc UI在like this的左上角显示徽标
问题:
我可以将x-log
添加到swagger.json文件中,但是将其添加到文件的错误部分。它必须位于info
部分中。
这就是我添加x-logo
public class XLogoDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
swaggerDoc.Extensions["x-logo"] = new { url = "https://URL/of/the/logo", altText = "Company Logo" };
}
}
SwaggerDoc
services.AddSwaggerGen(options =>
{
options.DocumentFilter<XLogoDocumentFilter>();
});
实际
{
"swagger": "2.0",
"info": {
"version": "v1",
"title":"Sample REST API"
},
"x-logo": {
"url": "https://rebilly.github.io/ReDoc/petstore-logo.png",
"altText": "Aimia Logo"
}
}
预期
{
"swagger": "2.0",
"info": {
"version": "v1",
"title":"Sample REST API",
"x-logo": {
"url": "https://rebilly.github.io/ReDoc/petstore-logo.png",
"altText": "Aimia Logo"
}
},
}
非常感谢在x-logo
中添加swagger.json文件正确部分的帮助或建议。
答案 0 :(得分:2)
.NET Core 2.2及更高版本
public class XLogoDocumentFilter : IDocumentFilter
{
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
// need to check if extension already exists, otherwise swagger
// tries to re-add it and results in error
if (!swaggerDoc.Info.Extensions.ContainsKey("x-logo"))
swaggerDoc.Info.Extensions.Add("x-logo", new OpenApiObject
{
{"url", new OpenApiString("https://www.petstore.com/assets/images/logo.png")},
{"backgroundColor", new OpenApiString("#FFFFFF")},
{"altText", new OpenApiString("PetStore Logo")}
});
}
}
答案 1 :(得分:1)
输入问题后,我自己找到了解决方案。与其直接将扩展名添加到swaggerDoc,不如将扩展名添加到swaggerDoc.Info对象。
public class XLogoDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
// need to check if extension already exists, otherwise swagger
// tries to re-add it and results in error
if (!swaggerDoc.Info.Extensions.ContainsKey("x-logo"))
{
swaggerDoc.Info.Extensions.Add("x-logo", new {
url = "https://URL/To/The/Logo",
altText = "Logo",
});
}
}
}
答案 2 :(得分:1)
较新版本的Swashbuckle在SwaggerDoc设置中支持此功能:
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = ApiDescription,
Version = "v1",
Extensions = new Dictionary<string, IOpenApiExtension>
{
{"x-logo", new OpenApiObject
{
{"url", new OpenApiString("https://blah.com/logo")},
{ "altText", new OpenApiString("The Logo")}
}
}
}
});