1. 创建一个Config文件夹,再文件夹下创建一个类,我这点取名 DefaultValue.cs
using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; namespace WebApiTest1.Config { public class DefaultValue : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if(schema == null) { return; } foreach (var item in schema.Properties) {
//如果是字符串类型,且默认值是null,将值设置为空
if(item.Value.Type == "string" && item.Value.Default == null) { item.Value.Default = new OpenApiString(""); //设置默认值为空 } } } } }
2. Program.cs文件中配置
builder.Services.AddSwaggerGen(options => { options.SchemaFilter<DefaultValue>(); });
3. 定义的接口
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WebApiTest1.Model; namespace WebApiTest1.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class ValuesController : ControllerBase { [HttpPost] public string SearchUserInfo(SearchUsers req) { return "返回查询的信息"; } } }
4. SearchUsers.cs文件
namespace WebApiTest1.Model { public class SearchUsers { public int Id { get; set; } public string Name { get; set; } public char Sex { get; set; } } }
标签:webapi,默认值,Microsoft,item,WebApiTest1,using,swagger,public From: https://www.cnblogs.com/tlfe/p/18225383