如何在从以下 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);
虚张声势生成订单方向作为必需参数。我希望它是可选的,并向客户端指示默认值(不确定 swagger 是否支持此功能(。
我不喜欢使属性类型为空。还有其他选择吗?理想情况下使用内置类...
我使用Swashbuckle.AspNetCore - https://learn.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;
}
}
这是在 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; }
}
以下是招摇的 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
测试项目的源代码在这里:
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);
}
适用于 ASP.net MVC5,代码对.Net Core无效
1-定义自定义属性如下
public class SwaggerDefaultValueAttribute: Attribute
{
public SwaggerDefaultValueAttribute(string param, string value)
{
Parameter = param;
Value = value;
}
public string Parameter {get; set;}
public string Value {get; set;}
}
2-定义一个招摇操作过滤器类
public class AddDefaulValue: IOperationFilter
{
void IOperationFilter.Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null || !operation.parameters.Any())
{
return;
}
var attributes = apiDescription.GetControllerAndActionAttributes<SwaggerDefaultValueAttribute>().ToList();
if (!attributes.Any())
{
return;
}
foreach(var parameter in operation.parameters)
{
var attr = attributes.FirstOrDefault(it => it.Parameter == parameter.name);
if(attr != null)
{
parameter.@default = attr.Value;
}
}
}
}
3-在Swagger配置文件中注册操作过滤器
c.OperationFilter<AddDefaultValue>();
4-使用属性装饰控制器方法
[SwaggerDefaultValue("param1", "AnyValue")]
public HttpResponseMessage DoSomething(string param1)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
第一种方法
根据这里的答案之一,您应该能够简单地将以下内容添加到您的模型中,尽管我尚未验证这一点:
public class ExternalJobCreateViewModel
{
///<example>Bob</example>
public string CustomFilename { get; set; }
...etc
第二种方法
在 .net 6 中,我使用了以下内容:
public class MyFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.OperationId.Equals("somecontroller_somepath", StringComparison.OrdinalIgnoreCase))
{
operation.Parameters.Clear();
operation.Parameters = new List<OpenApiParameter>
{
new OpenApiParameter()
{
Name = "document-name",
Schema = new OpenApiSchema()
{
Type = "string",
},
Example = new Microsoft.OpenApi.Any.OpenApiString("docName1"),
In = ParameterLocation.Query
},
new OpenApiParameter()
{
Name = "user-email",
Schema = new OpenApiSchema()
{
Type = "string",
},
Example = new Microsoft.OpenApi.Any.OpenApiString("elvis.presley@somemail.com"),
In = ParameterLocation.Query
},
new OpenApiParameter()
{
Name = "account-type-id",
Schema = new OpenApiSchema()
{
Type = "string",
},
Example = new Microsoft.OpenApi.Any.OpenApiString("2"),
In = ParameterLocation.Query
}
};
}
}
}
然后在程序中.cs
builder.Services.AddSwaggerGen(options =>
{
... other stuf
options.OperationFilter<MyFilter>();
第三种方法
我从未使用过此代码,因此未进行测试
在 .net 6 中,捎带了 Sameh 的答案......
要使用多个属性,请按如下方式装饰属性类:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class SwaggerDefaultValueAttribute : Attribute
{
... etc
对于 6.5.0 的虚张声势,我认为属性是这样的:
public class AddDefaulValueFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if (operation.Parameters == null || !operation.Parameters.Any())
{
return;
}
context.ApiDescription.TryGetMethodInfo(out var x);
if (x != null)
{
return;
}
var attributes = x!.GetCustomAttributes<SwaggerDefaultValueAttribute>().ToList();
if (!attributes.Any())
{
return;
}
foreach (var parameter in operation.Parameters)
{
var attr = attributes.FirstOrDefault(it => it.Parameter == parameter.Name);
if (attr != null)
{
parameter.Schema.Default = new OpenApiString(attr.Value);
}
}
}
}
由于我试图将其用于多部分消息的正文参数,因此我不得不做这样的事情,但使用风险自负:
public class AddDefaulValueFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
if(operation.RequestBody == null)
{
return;
}
var keys = operation.RequestBody.Content.Where(val => val.Key == "multipart/form-data").Take(1).ToList();
if(!keys.Any())
{
return;
}
var props = keys.FirstOrDefault().Value.Schema.Properties;
if (props == null || !props.Any())
{
return;
}
context.ApiDescription.TryGetMethodInfo(out var x);
if (x == null)
{
return;
}
var attributes = x!.GetCustomAttributes<SwaggerDefaultValueAttribute>().ToList();
if (!attributes.Any())
{
return;
}
foreach (var prop in props)
{
var attr = attributes.FirstOrDefault(it => it.Parameter == prop.Key);
if (attr != null)
{
prop.Value.Default = new OpenApiString(attr.Value);
}
}
}
}
在 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
招摇 - 枚举
招摇 - 解锁规范:默认关键字