【问题标题】:Custom fields in swagger generated API documentation in C#在 C# 中大摇大摆地生成 API 文档中的自定义字段
【发布时间】:2022-11-08 17:38:29
【问题描述】:

我有一个 ASP.NET 6 API 项目,我正在使用 Swagger 生成文档。

现在的问题是客户想要一个在端点级别具有附加属性的 YAML 文件,如下所示(我将它们命名为 x-customer-prop-....):

...
/Commodities/Categories/List:
    get:
      x-customer-prop-production-ready: true
      x-customer-prop-access-policy:  open
      x-customer-prop-data-classification: public
      x-customer-prop-api-pattern: Hey Jude
      tags:
        - Commodities
      summary: Provides the list of categories.
      description: Categories are matched with high level commodity classification at level 1. \n\nNo mandatory parameter.
      parameters:
        - name: countryCode
          in: query
          description: The code to identify the country. It can be a ISO-3166 Alpha 3 code
          schema:
            type: string
        - name: categoryName
          in: query
          description: The name, even partial and case insensitive, of a commodity category.
          schema:
            type: string

如何为每个端点生成这些属性?

如何生成 YAML 而不是常规 JSON?

目前,为了生成文档,我使用方法顶部的属性:

/// <summary>
/// Provides the list of categories.
/// </summary>
/// <remarks>
/// Categories are matched with high level commodity classification at level 1. \n\nNo mandatory parameter.
/// </remarks>
/// <param name="countryCode">The code to identify the country. It can be a ISO-3166 Alpha 3 code</param>
/// <param name="categoryName">The name, even partial and case insensitive, of a commodity category.</param>
/// <param name="categoryID">The exact ID of a Commodity, as found in /Commodities/List.</param>
/// <param name="page">page number for paged results</param>
/// <param name="format">Output format: [JSON|CSV] Json is the default value</param>        /// 
/// <returns></returns>
[HttpGet]
[ApiVersion("1.0")]
[Route("Categories/List")]
[ProducesResponseType(typeof(BusinessLogic.Dto.PagedCommodityListDTO), 200)]
[ProducesResponseType(typeof(BusinessLogic.Dto.BadRequestDTO), 400)]
public async Task<IActionResult> GetCategoriesList(string? countryCode, string? categoryName, int categoryID = 0, int page = 1, string format = "json")
....
}

在启动时,我通过以下方式添加招摇生成:

services.AddSwaggerGen(
    options =>
    {
        options.DocumentFilter<Swagger.CustomModelDocumentFilter>();
        options.SwaggerDoc("v1.0", new OpenApiInfo { 
            Title = "XXXX API", 
            Description= "API Documentation of the XXXXXX platform: ...",
            Contact = new OpenApiContact()
            {
                Name= "XXX-INFO",
                Email= "email@somewhere.com"
            },
            Version = "v1.0" });
        options.IncludeXmlComments(XmlCommentsFilePath, true);
    });

其中 CustomModelDocumentFilter 类用于添加其他属性,但仅在根级别:

public class CustomModelDocumentFilter : IDocumentFilter
{
    public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
    {
        swaggerDoc.Extensions.Add("x-customer-root-prop-xxx", new CustomExtensionValue("false"));
    }
}

【问题讨论】:

  • 开放 api 模式是否支持定义此类属性?
  • @CodingMytra 是的

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


【解决方案1】:

您也可以在端点级别添加扩展。 你需要像下面这样使用 OperationFilter

public class MyOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        operation.Extensions.Add("x-customer-root-prop-xxx", new Microsoft.OpenApi.Any.OpenApiString("false"));
    }
}

options.DocumentFilter<MyOperationFilter>();

再次运行并查看 json 文档后,您可以看到每个端点的这些属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 2019-02-05
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 2017-10-11
    • 2015-12-14
    相关资源
    最近更新 更多