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; } } }