swashbuckle - 如何使用 Swashbuckle.AspNetCore 为 ReDoc 添加 x-code-samples?

标签 swashbuckle redoc

添加 x-code-samples 的最佳方式是什么?对于 ReDoc通过 Swashbuckle.AspNetCore.Annotations 到 swagger.json ?

编辑(2019 年 3 月 30 日)

我希望这是一个更好的解释。 Swashbuckle.AspNetCore 中有一种方法可以将内容添加到生成的 swagger.json 中。

记录的内容 (示例来自 GitHub-Page):

[HttpPost]

[SwaggerOperation(
    Summary = "Creates a new product",
    Description = "Requires admin privileges",
    OperationId = "CreateProduct",
    Tags = new[] { "Purchase", "Products" }
)]
public IActionResult Create([FromBody]Product product)

关于我想要实现的目标

我想做的是这样的:

[MyCustomSwaggerOperation(
    x-code-samples = [
        {
          "lang": "CSharp", 
          "source": "console.log('Hello World');"
        }, 
        {
          "lang": "php",
          "source": ...
        }
    ]
)]
public IActionResult Create([FromBody]Product product)

最佳答案

这是一个 IDocumentFilter,它将“x-code-samples”注入(inject)参数

public class InjectSamples : IDocumentFilter
{
    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
        PathItem path = swaggerDoc.Paths.Where(x => x.Key.Contains("Values")).First().Value;
        path.Post.Parameters.FirstOrDefault().Extensions.Add("x-code-samples", "123456");
    }
}

是的,您可以使用注释使所有这些变得复杂,但是 Swashbuckle 不支持开箱即用的“x-code-samples”,因此您必须创建自己的,并在 iDocFilter 上使用它。

在评论中,您不断指出 IDocumentFilters 是在生成 swagger 文档后添加的,是的,我们希望如此!

生成的 swagger.json 看起来像这样:

"post": {
    "tags": [ "Values" ],
    "operationId": "ApiValuesPost",
    "consumes": [ "application/json" ],
    "produces": [],
    "parameters": [
        {
            "name": "value",
            "in": "body",
            "required": false,
            "schema": { "type": "string" },
            "x-code-samples": "123456"
        }
    ],
    "responses": {
        "200": { "description": "Success" }
    }
}   

关于swashbuckle - 如何使用 Swashbuckle.AspNetCore 为 ReDoc 添加 x-code-samples?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55329325/

相关文章:

asp.net-mvc-5 - SwaggerRequestExample 属性在 ASP.NET MVC 5 (.NET Framework 4.5.2) 中不起作用

fluentvalidation - 无法从 ISchemaFilter 中的 ServiceProvider 获取 FastEndpoint 验证器实例的 IValidator<T>

c# - ASP.NET Core 2.1 Swagger(swashbuckle) Url模板可选参数

c# - .NET 5 中的 System.Text.Json 字段序列化未在 Swashbuckle API 定义中显示

swagger - 使用 Swagger 生成的客户端时, header 中的硬编码 Api 键值

c# - 如何在 Swashbuckle 中更改 POST 和 PUT 的必填字段?

具有Swagger或其他文档的带有定义参数(request.POST)的Django Rest Framework自定义POST URL端点

django - 如何通过 drf-yasg 为 ReDoc 添加 x-server & x-taggroups