如何在以下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);
Swashbuckle生成OrderDirection作为必需参数.我想成为可选项并向客户端指示默认值(不确定swagger是否支持此功能).
我不喜欢使属性类型可以为空.还有其他选择吗?理想情况下使用内置类…
我使用Swashbuckle.AspNetCore – https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
解决方法
我总是在param上设置默认值,如下所示:
public class TestPostController : ApiController { public decimal Get(decimal x = 989898989898989898,decimal y = 1) { return x * y; } }
这就是swagger-ui的样子:
http://swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get
UPDATE
在对评论进行讨论之后,我更新了Swagger-Net以通过反射读取DefaultValueAttribute
这是我正在使用的示例类:
public class MyTest { [MaxLength(250)] [DefaultValue("HelloWorld")] public string Name { get; set; } public bool IsPassing { get; set; } }
这是swagger json的样子:
"MyTest": { "type": "object","properties": { "Name": { "default": "HelloWorld","maxLength": 250,"type": "string" },"IsPassing": { "type": "boolean" } },"xml": { "name": "MyTest" } },
Swagger-Net的源代码在这里:
https://github.com/heldersepu/Swagger-Net