Swagger default value for parameter

非 Y 不嫁゛ 提交于 2019-12-05 07:06:22

I've always set the default on the param itself like this:

public class TestPostController : ApiController
{
    public decimal Get(decimal x = 989898989898989898, decimal y = 1)
    {
        return x * y;
    }
}

Here is how that looks like on the swagger-ui:
http://swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get


UPDATE

Following the discussion on the comments I updated Swagger-Net to read the DefaultValueAttribute via reflection Here is the sample class I'm using:

public class MyTest
{
    [MaxLength(250)]
    [DefaultValue("HelloWorld")]
    public string Name { get; set; }
    public bool IsPassing { get; set; }
}

and here is how the swagger json looks like:

"MyTest": {
  "type": "object",
  "properties": {
    "Name": {
      "default": "HelloWorld",
      "maxLength": 250,
      "type": "string"
    },
    "IsPassing": {
      "type": "boolean"
    }
  },
  "xml": {
    "name": "MyTest"
  }
},

The Source code of Swagger-Net is here:
https://github.com/heldersepu/Swagger-Net

And the source code for the test project is here:
https://github.com/heldersepu/SwashbuckleTest

Setting the default parameter value works like this if you can do it in your controller

// GET api/products
[HttpGet]
public IEnumerable<Product> Get(int count = 50)
{
    Conn mySqlGet = new Conn(_connstring);
    return mySqlGet.ProductList(count);
}

In the YAML file, you can define which properties should be required. This example is from a NSwag configuration.

/SearchPendingCases:
    post:
      summary: Search pending cases
      description: Searches for pending cases and orders them
      parameters:
        - in: body
          name: SearchQuery 
          required: true
          schema:
            type: object
            required:
              - OrderBy
              # do not include OrderDirection here because it is optional
            properties:
              OrderBy:
                description: Name of property for ordering
                type: string
                # you can remove the following two lines 
                # if you do not want to check the string length
                minLength: 1    
                maxLength: 100
              OrderDirection:
                description: Optional order direction, default value: Descending
                type: string
                enum: [Ascending, Descending] # valid enum values
                default: Descending           # default value

Swagger - Enums

Swagger - Unlocking the Spec: The default keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!