You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core Web API如何在Swagger中设置默认日期格式为yyyy-MM-dd

在ASP.NET Core 6 Web API中修改Swagger日期字段显示格式

方法一:通过数据注解指定单字段格式

给目标DateTime字段添加[JsonFormat]注解(适配ASP.NET Core 6默认的System.Text.Json序列化),同时搭配[DisplayFormat]确保Swagger识别并展示预期格式:

using System.Text.Json.Serialization;
using System.ComponentModel.DataAnnotations;

public class PaymentRequestModel
{
    public string ReferenceNumber { get; set; }

    [JsonFormat(JsonSerializerOptions.Default, "yyyy-MM-dd")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime StartDate { get; set; }

    [JsonFormat(JsonSerializerOptions.Default, "yyyy-MM-dd")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime EndDate { get; set; }
}

配置后,Swagger的示例会自动更新为"YYYY-MM-DD"格式,同时接口实际返回的JSON日期也会遵循该格式。

方法二:自定义Swagger Schema过滤器(全局生效)

如果需要批量处理所有DateTime类型字段,可创建自定义过滤器统一修改Swagger的Schema定义:

  1. 编写过滤器类:
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;

public class DateTimeSchemaFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (context.Type == typeof(DateTime) || context.Type == typeof(DateTime?))
        {
            schema.Type = "string";
            schema.Format = "date";
            schema.Example = new Microsoft.OpenApi.Any.OpenApiString("YYYY-MM-DD");
        }
    }
}
  1. 在Program.cs中注册Swagger时添加该过滤器:
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Payment API", Version = "v1" });
    // 注入自定义日期格式过滤器
    c.SchemaFilter<DateTimeSchemaFilter>();
});

此方法会全局修改所有DateTime(包括可空DateTime)字段在Swagger中的显示样式,示例值固定为"YYYY-MM-DD",同时符合OpenAPI的date格式规范。

方法三:全局配置JSON序列化规则(同步接口返回与Swagger示例)

如果希望接口返回的JSON日期统一使用yyyy-MM-dd格式,且Swagger示例同步匹配,可在Program.cs中配置全局序列化选项:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        // 配置DateTime序列化格式
        options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonConverter<DateTime>
        (
            writeFunc: (writer, value) => writer.WriteStringValue(value.ToString("yyyy-MM-dd")),
            readFunc: (reader) => DateTime.Parse(reader.GetString()!)
        ));
        // 可选:保留驼峰命名等其他序列化规则
        options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
    });

配置完成后,Swagger会根据全局序列化规则自动调整示例格式,同时接口返回的日期数据也会统一为yyyy-MM-dd格式。


内容的提问来源于stack exchange,提问作者Ayobamilaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:18:37