问题描述
如何为以下 API 生成的 swagger 中的属性定义默认值?
How do I define default value for property in swagger generated from following API?
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 generates OrderDirection as required parameter. I would like to be it optional and indicate to client the default value (not sure if swagger supports this).
我不喜欢让属性类型可以为空.还有其他选择吗?理想情况下使用内置类...
I don't like making the property type nullable. Is there any other option? Ideally using built in classes...
我使用 Swashbuckle.AspNetCore - https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
I use Swashbuckle.AspNetCore - https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio
推荐答案
我总是这样设置参数本身的默认值:
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;
}
}
这是 swagger-ui 上的样子:
http://swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get
Here is how that looks like on the swagger-ui:
http://swashbuckletest.azurewebsites.net/swagger/ui/index#/TestPost/TestPost_Get
在讨论了评论后,我更新了 Swagger-Net 以阅读 <代码>DefaultValueAttribute 通过反射这是我正在使用的示例类:
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; }
}
这是招摇 json 的样子:
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"
}
},
Swagger-Net的源代码在这里:
https://github.com/heldersepu/Swagger-Net
测试项目的源代码在这里:
https://github.com/heldersepu/SwashbuckleTest
And the source code for the test project is here:
https://github.com/heldersepu/SwashbuckleTest
这篇关于参数的 Swagger 默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!