Lie*_*ero 6 c# swagger swashbuckle asp.net-core asp.net-core-2.0
如何在以下API生成的swagger中定义属性的默认值?
public class SearchQuery
{
public string OrderBy { get; set; }
[DefaultValue(OrderDirection.Descending)]
public OrderDirection OrderDirection { get; set; } = OrderDirection.Descending;
}
public IActionResult SearchPendingCases(SearchQuery queryInput);
Run Code Online (Sandbox Code Playgroud)
Swashbuckle生成OrderDirection作为必需参数.我想成为可选项并向客户端指示默认值(不确定swagger是否支持此功能).
我不喜欢使属性类型可以为空.还有其他选择吗?理想情况下使用内置类...
我使用Swashbuckle.AspNetCore - https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
我总是像这样设置参数本身的默认值:
public class TestPostController : ApiController
{
public decimal Get(decimal x = 989898989898989898, decimal y = 1)
{
return x * y;
}
}
Run Code Online (Sandbox Code Playgroud)
这是 swagger-ui 上的样子:http :
//swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get
在对评论的讨论之后,我更新了Swagger-Net以阅读DefaultValueAttribute通过反射这是我正在使用的示例类:
public class MyTest
{
[MaxLength(250)]
[DefaultValue("HelloWorld")]
public string Name { get; set; }
public bool IsPassing { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是 swagger json 的样子:
"MyTest": {
"type": "object",
"properties": {
"Name": {
"default": "HelloWorld",
"maxLength": 250,
"type": "string"
},
"IsPassing": {
"type": "boolean"
}
},
"xml": {
"name": "MyTest"
}
},
Run Code Online (Sandbox Code Playgroud)
Swagger-Net的源代码在这里:https :
//github.com/heldersepu/Swagger-Net
测试项目的源代码在这里:https :
//github.com/heldersepu/SwashbuckleTest
如果您可以在控制器中执行此操作,则设置默认参数值的工作方式如下
// GET api/products
[HttpGet]
public IEnumerable<Product> Get(int count = 50)
{
Conn mySqlGet = new Conn(_connstring);
return mySqlGet.ProductList(count);
}
Run Code Online (Sandbox Code Playgroud)
Geo*_*der -3
在 YAML 文件中,您可以定义需要哪些属性。此示例来自 NSwag 配置。
/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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11840 次 |
| 最近记录: |