Swagger default value for parameter(参数的 Swagger 默认值)
问题描述
如何为以下 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 默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:参数的 Swagger 默认值
基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
