【问题标题】:Provide a complex object for a SwaggerExample?为 SwaggerExample 提供复杂对象?
【发布时间】:2022-01-03 05:56:42
【问题描述】:

我们正在使用 Swagger.Net 包来帮助我们编写文档。

我正在尝试将要自动生成的请求数据添加到我的文档中,并且正在查看提供此代码块的 this answer

[SwaggerExample("id", "123456")]
public IHttpActionResult GetById(int id)
{...}

我不确定如何将 int 转换为更复杂的对象。例如:

[Route("SaveCustomThing"), HttpPost]
[SwaggerExample("thing", ???)]
public HttpResponseMessage SaveCustomThing([FromBody] Thing thing)
{...}

如何在SwaggerExample 属性中传递预配置的Thing 对象?

【问题讨论】:

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


    【解决方案1】:

    查看属性(SwaggerExample)带两个参数的代码:

            public SwaggerExampleAttribute(string parameterName, object example)
            {
                this.ParameterName = parameterName;
                this.Example = example;
            }
    

    https://github.com/heldersepu/Swagger-Net/blob/6afdb0c1ba611273f27e8a904ec2bb06a630b1b4/Swagger.Net/Swagger/Annotations/SwaggerExampleAttribute.cs#L16

    我们可以看到第一个是字符串,而第二个是对象...
    理论上你应该可以在那里传递任何东西。


    我会推荐另一种选择,如果您有像 Thing 这样的复杂模型,您应该考虑在模型上添加示例,我们可以在那里做更多的事情......正如您在下面看到的,我们可以添加描述,示例值和其他一些装饰器,我们可以限制值的范围,代码如下:

        /// <summary>
        /// ## Geographic coordinates
        /// ___
        /// A **geographic coordinate system** is a coordinate system used in geography that enables every location on Earth to be specified by a set of numbers
        /// </summary>
        public class Location
        {
            /// <summary>**Latitude**: a geographic coordinate that specifies the north–south position of a point on the Earth's surface.</summary>
            /// <example>25.85</example>
            [Range(-90, 90)]
            public float Lat { get; set; }
    
            /// <summary>**Longitude**: a geographic coordinate that specifies the east-west position of a point on the Earth's surface.</summary>
            /// <example>-80.27</example>
            [Range(-180, 180)]
            public float Lon { get; set; }
        }
    

    http://swagger-net-test.azurewebsites.net/swagger/ui/index#/Location/Location_Get2

    【讨论】:

    • 我看不出属性是如何被修饰的。我仍然坚持使用[SwaggerExample("location", Location???)] 我不知道我为一个对象传递了什么。
    • 没有SwaggerExample("location" 那些在每个单独属性的模型上/// &lt;example&gt;25.85&lt;/example&gt; 我在那里添加了代码示例
    猜你喜欢
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多