一、 背景
[HttpPost]
public string Test(SearchReq search)
{
return "ok" + search.Name;
}
从 swagger 中可以看出, 字符串若为空,则默认提交string,若要修改为指定字符,可修改过滤器
二、修改策略
2.1 创建过滤器
通过类型设置默认值
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace WebApplication2.Conf
{
public class Filter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if(schema == null)
{
return;
}
var obj = schema;
foreach(var item in obj.Properties)
{
if (item.Value.Type == "string" && item.Value.Default == null)
{
item.Value.Default = new OpenApiString("");
}
}
}
}
}
通过属性名设置默认值
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace WebApplication2.Conf
{
public class Filter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if(schema == null)
{
return;
}
var obj = schema;
foreach(var item in obj.Properties)
{
if (item.Value.Type == "string" && item.Value.Default == null)
{
item.Value.Default = new OpenApiString("");
}
if (item.Key == "pageIndex")
{
item.Value.Default = new OpenApiInteger(1);
}
else if(item.Key =="pageSize")
{
item.Value.Default = new OpenApiInteger(10);
}
}
}
}
}
通过属性修改默认值
修改实体类
using System.ComponentModel;
namespace WebApplication2.Model
{
public class SearchReq
{
[DefaultValue("zhangsna")]
public String Name { get; set; }
public string Description { get;set; }
public int PageIndex { get; set; }
public int PageSize { get; set; }
}
}
修改过滤器
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.ComponentModel;
using System.Reflection;
namespace WebApplication2.Conf
{
public class Filter : ISchemaFilter
{
public void Apply(OpenApiSchema schema, SchemaFilterContext context)
{
if(schema == null)
{
return;
}
var obj = schema;
foreach(var item in obj.Properties)
{
if (item.Value.Type == "string" && item.Value.Default == null)
{
item.Value.Default = new OpenApiString("");
}
if (item.Key == "pageIndex")
{
item.Value.Default = new OpenApiInteger(1);
}
else if(item.Key =="pageSize")
{
item.Value.Default = new OpenApiInteger(10);
}
// 通过特性来实现
DefaultValueAttribute defaultValue = (context.ParameterInfo?.GetCustomAttribute());
if(defaultValue != null)
{
item.Value.Example = (IOpenApiAny)defaultValue.Value;
}
}
}
}
}
2.2 加载过滤器
builder.Services.AddSwaggerGen(option =>
{
// 设置对象类型参数默认值
option.SchemaFilter();
});