【问题标题】:Swagger - how attach an example to particular end-pointSwagger - 如何将示例附加到特定端点
【发布时间】:2022-01-12 00:00:08
【问题描述】:

我正在开发 API,我的控制器只返回 JsonDocument 而不是 DTO。

我需要为 API 文档提供一些响应示例。但是示例应该专门针对特定的端点。

我创建了示例提供程序IExampleProvider<JsonDocument> - 不幸的是,该示例为所有 JsonDocument 填充,而不是唯一一个由属性修饰的示例: [SwaggerResponseExample(200, typeof(MySpecificResponseExample))]

即使没有指定上述属性,也包括示例文档。

Startup.cs:

c.ExampleFilters();
c.OperationFilter<AddResponseHeadersFilter>();

services.AddSwaggerExamplesFromAssemblyOf&lt;Startup&gt;();

示例提供者:

public class (MySpecificResponseExample))] : IExamplesProvider<JsonDocument>
    {
        public JsonDocument GetExamples()
        {
            return JsonDocument.Parse(@"Example JSON is here.");
        }
    }

控制器:

        [HttpGet]
        [ProducesResponseType(typeof(JsonDocument), 200)]
        [SwaggerResponseExample(200, typeof(MySpecificResponseExample))]
        public async Task<IActionResult> GetSomething() {}

如何仅将示例包含到具有特定属性的端点?我有另一个指定 [ProducesResponseType(typeof(JsonDocument), 200)] 的端点,但我想省略 MySpecificResponseExample

【问题讨论】:

    标签: c# asp.net-web-api swagger-ui .net-5


    【解决方案1】:

    您不能通过 http 返回 JsonDocument ,因为它需要转换为 json ,所以我认为双分割和取消分割没有任何意义,您最好尝试一下,并在获得 JsonDocument 时解析它。但我强烈建议改用 JObject 或 JArray

     public JsonResult GetExamples()
     {
         return new JsonResult( @"Example JSON is here.");
     }
    

    【讨论】:

    • 好的 - 我可以返回 JsonResult,但问题是一样的 - 我有一种用于多个端点的类型。我只想为一个端点提供示例响应。端点 A - 返回类型 Xyz,端点 B - 返回类型 xyz 以及 - 我需要为端点 A 提供示例响应,但我不想为端点 B 提供任何示例。
    • @WymyslonyNick 如果需要帮助,您必须发布所有代码链。不只是几行。如果你有这么多问题,想想你是否真的需要一个 Swagger。
    猜你喜欢
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多