Swagger:使用 ref 添加描述

Swagger: Add description with ref

我想为引用了他的定义的对象添加描述 属性。类似的东西:

      newCreditCard:
        type: object
        properties:
          billingPhone:
            description: Phone number of the card holder
            $ref: "#/definitions/PhoneNumber"

但编辑警告说描述属性将被跳过:

Extra JSON Reference properties will be ignored: description

我发现了一个不太优雅的解决方法,它适用于编辑器,但不适用于 Swagger UI(不确定这可能是由于最近更新到 3.0.2 版本的 Swagger UI)

      newCreditCard:
        type: object
        properties:
          billingPhone:
            description: Phone number of the card holder
            allOf:
            - $ref: "#/definitions/PhoneNumber"

在你的Swaggers规范中你是怎么做到的?

感谢您的帮助!

您可以简单地将 description 属性 移动到 PhoneNumber 的定义中。您的原始 post 未显示您如何定义 PhoneNumber,但此代码段在没有警告的情况下验证:

definitions:
  phoneNumber:
    type: string
    description: Phone number of the card holder

  newCreditCard:
    type: object
    properties:
      billingPhone:
        $ref: "#/definitions/phoneNumber"

如果这个答案不是您要找的,请重述问题。我们需要知道您想要完成什么。

如果您将任何内容添加到 $ref 的同一级别,它将被忽略。

json $ref 定义 https://datatracker.ietf.org/doc/html/draft-pbryan-zyp-json-ref-03#section-3

正确的方法是在引用对象中提供描述。

尽管它不符合 JSON 标准。 如果您使用 Swashbuckle 来生成您的招摇。 我利用了架构的“扩展”属性。 并设法创建了一个 swagger JSON,具有 $ref 和扩展属性。


var refSchema = new OpenApiSchema
{      
     //Reference = new OpenApiReference { ExternalResource = referenceLink, Type = ReferenceType.Link }, this wont work and omit all your other properties
    Extensions = new Dictionary<string, IOpenApiExtension>
    {
        { "$ref" , new OpenApiString(referenceLink) } // adding ref as extension cause according to JSON standards $ref shouldnt have any other properties
    },
    Description = prop.Value.Description,
    ReadOnly = prop.Value.ReadOnly,
    Required = prop.Value.Required,
    Type = prop.Value.Type,
    Example = prop.Value.Example,
};