Azure Function(.NET 6)+Swashbuckle:DateOnly无法显示为$date格式求助
解决.NET 6 Azure Function中Swashbuckle对DateOnly类型的Swagger Schema显示问题
在.NET 6环境的Azure Function中使用Swashbuckle组件时,实体类中的DateOnly字段会被生成分解为包含year、month等属性的复杂对象,而我们期望它显示为string($date)格式的Schema。
解决方案:自定义Schema过滤器
通过实现ISchemaFilter接口,覆盖Swashbuckle对DateOnly类型的Schema生成逻辑,具体步骤如下:
- 创建自定义Schema过滤器类
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; public class DateOnlySchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { // 处理DateOnly和可空DateOnly类型 var targetType = context.Type.IsGenericType && context.Type.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(context.Type) : context.Type; if (targetType == typeof(DateOnly)) { schema.Type = "string"; schema.Format = "date"; // 清空自动生成的子属性 schema.Properties.Clear(); schema.Required.Clear(); // 标记可空类型 schema.Nullable = context.Type.IsGenericType && context.Type.GetGenericTypeDefinition() == typeof(Nullable<>); } } }
- 在Azure Function配置中注册过滤器
在Program.cs的服务配置环节,将自定义过滤器添加到Swagger生成器:
var builder = new HostBuilder(); builder.ConfigureFunctionsWorkerDefaults(); builder.ConfigureServices(services => { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Azure Functions API", Version = "v1" }); // 注册自定义Schema过滤器 c.SchemaFilter<DateOnlySchemaFilter>(); }); }); var host = builder.Build(); host.Run();
- 验证效果
重新启动Azure Function并访问Swagger UI,DateOnly类型的字段将显示为:
startDate string($date)
内容的提问来源于stack exchange,提问作者Varinder Gupta
相关产品推荐
相关产品推荐

