如何在 ASP.NET Core 中正确设置 Swagger 示例?

Dav*_*ing 10 c# swagger .net-core asp.net-core openapi

我的目标:

为了仅在使用 SwaggerRequestExample 注释的端点上正确设置 OpenApi JSON 文档中的请求示例,而不是端点响应或缺少此属性的其他端点。

预期结果:

"post": {
    "tags": [
      "Address"
    ],
    "requestBody": {
      "content": {
        },
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Address"
          },
          "example": {"id":"995ace6e-33d5-4efd-860e-b653fef60dad","binaryAddress":246,"distance":123}
        }
        }
      }
    },
    "responses": {
      "200": {
        "description": "Success",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Address"
            }
          }
          }
        }
      }
Run Code Online (Sandbox Code Playgroud)

实际结果:

"post": {
    "tags": [
      "Address"
    ],
    "requestBody": {
      "content": {
        },
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/Address"
          },
          "example": {"id":"995ace6e-33d5-4efd-860e-b653fef60dad","binaryAddress":246,"distance":123}
        }
        }
      }
    },
    "responses": {
      "200": {
        "description": "Success",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Address"
            },
            "example": {"id":"a04c827c-5e29-4940-8bee-89f8e07af5a8","binaryAddress":246,"distance":123}
          }
          }
        }
      }
Run Code Online (Sandbox Code Playgroud)

错误消息:

我没有遇到任何错误消息。

我尝试过的:

我已经尝试了几种启动和控制器属性配置来尝试获得预期的行为,但无法获得预期的结果。这是我期望工作的配置,但不幸的是不是:

Startup.cs 片段

services.AddSwaggerGen(options =>
{
    options.MapType<ushort>(() => OpenApiSchemaFactory.MapInteger(typeof(ushort)));
});
services.ConfigureOptions<ConfigureSwaggerOptions>(); // calls .SwaggerExamples()
services.AddSwaggerGenNewtonsoftSupport();
services.AddSwaggerExamples();
services.AddSwaggerExamplesFromAssemblyOf<AddressExample>();
Run Code Online (Sandbox Code Playgroud)

AddressController.cs 减去其他端点

[ApiVersion("1.0")]
[ApiController]
[Route("api/v{api-version:apiVersion}/[controller]")]
public class AddressController : ControllerBase
{
    [HttpPost]
    [Ok(typeof(Address))]
    [BadRequest]
    [SwaggerRequestExample(typeof(Address), typeof(AddressExample))]
    public IActionResult AddAddress([FromBody] Address address)
    {
        return Ok(_service.AddAddress(address)); // The service is just a pass-through layer at the moment
    }
}
Run Code Online (Sandbox Code Playgroud)

地址示例.cs

public class AddressExample : IExamplesProvider<Address>
{
    public Address GetExamples()
    {
        return new Address
        {
            Id = Guid.NewGuid(),
            BinaryAddress = 246L,
            Distance = 123
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

基于上面的代码,我只期望设置请求示例。但是,响应示例也已设置。对我来说更令人费解的是,不仅如此,在请求或响应中使用地址模型的任何端点也都设置了示例。

在我尝试正确配置时,我发现这一行

services.AddSwaggerExamplesFromAssemblyOf<AddressExample>();
Run Code Online (Sandbox Code Playgroud)

即使我不使用控制器端点上注释的 SwaggerRequestExample 属性,也会在地址模型的所有实例中设置定义的示例。

目前,我不知道如何正确设置开箱即用的 swagger 配置示例,而无需为使用相关模型的每个实例创建示例。

有人可以指出我正确的方向或提供一个应该有效的例子吗?谢谢。

编辑:我也非常乐意提供额外的代码

AC4*_*AC4 6

我也想知道这个问题,所以我深入研究了Swashbuckle的文档。事实证明,这是通过 XML 文档注释来处理的。不久前,这感觉非常笨拙。首先,您必须向 API 方法添加 XML 文档注释。我的看起来像这样:

在此输入图像描述

然后,您需要在项目的属性中打开 XML 文档文件生成:

在此输入图像描述

我的测试项目名为XcExample.Api.Sometext. 因为我将“文件路径”字段留空,所以当我编译时,它会XcExample.Api.Sometext.xml在二进制文件旁边放置一个名为的文件。

然后,要将这些数据包含在 OAS3/Swagger 生成中,您可以在 Program.cs 中找到如下所示的行: 在此输入图像描述 然后将该文件添加到生成信息中,如下所示: 在此输入图像描述

然后当你查看 Swagger UI 时,它看起来像这样: 在此输入图像描述

那么您的 OAS 文档路径部分如下所示:


"paths": {
    "/api/{id}/GetTogether/{word}/Concat": {
      "post": {
        "tags": [
          "Concat"
        ],
        "summary": "Get Some Text Together for a Party",
        "parameters": [
          {
            "name": "id",
            "in": "path",
            "description": "word index",
            "required": true,
            "style": "simple",
            "schema": {
              "type": "integer",
              "format": "int32"
            },
            "example": 9987
          },
          {
            "name": "word",
            "in": "path",
            "description": "indexed word",
            "required": true,
            "style": "simple",
            "schema": {
              "minLength": 2,
              "type": "string"
            },
            "example": "orange"
          }
        ],
        "requestBody": {
          "description": "words and puncuation",
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/Sentence"
              }
            },
            "text/json": {
              "schema": {
                "$ref": "#/components/schemas/Sentence"
              }
            },
            "application/*+json": {
              "schema": {
                "$ref": "#/components/schemas/Sentence"
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Success",
            "content": {
              "text/plain": {
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                }
              },
              "application/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                }
              },
              "text/json": {
                "schema": {
                  "type": "array",
                  "items": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

示例代码位于我的github 上的XcExample.Api.Sometext 项目中。