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

ASP.NET Core 3.1 System.Text.Json 自定义dd/MM/yyyy日期格式不生效求助

问题根因

  1. 提交的请求不是JSON格式
    你配置的AddJsonOptions仅对Content-Type: application/json的请求生效,如果你用的是form-data/x-www-form-urlencoded表单提交,系统不会走JSON序列化流程,自定义的JsonConverter完全不会触发。这时候ASP.NET Core默认用服务器当前线程的区域文化来解析日期,和你系统的日期格式绑定,所以改了系统格式就能正常运行,这是最常见的原因。如果确认是JSON请求,先检查请求头的Content-Type是否正确设置为application/json。

  2. JsonConverter本身的逻辑缺陷
    如果确认是JSON请求,那你的转换器逻辑有两处问题:

  • 非空DateTime转换器中,TryParseExact解析失败后直接调用reader.GetDateTime(),这个方法默认用的是系统区域文化解析,还是会受系统格式影响
  • Write方法没有按你需要的dd/MM/yyyy格式输出,返回给前端的格式会不统一

解决方案

情况1:使用表单提交(非JSON请求)

你需要配置全局的模型绑定日期解析规则,有两种方案可选:

方案A:配置全局文化为固定格式

在Startup.cs的ConfigureServices中添加如下配置:

services.Configure<RequestLocalizationOptions>(options =>
{
    var cultureInfo = new CultureInfo("en-GB"); // 英国文化默认日期格式就是dd/MM/yyyy
    cultureInfo.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
    options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture(cultureInfo);
    options.SupportedCultures = new List<CultureInfo> { cultureInfo };
    options.SupportedUICultures = new List<CultureInfo> { cultureInfo };
});

然后在Configure方法中启用请求本地化:

app.UseRequestLocalization();
方案B:自定义日期模型绑定器

如果不想改全局文化,可以单独为DateTime类型写自定义模型绑定器,逻辑和你之前的JsonConverter类似即可。

情况2:使用JSON提交

修正你的JsonConverter逻辑即可:

public class DateTimeConverter : JsonConverter<DateTime>
{
    private const string DateFormat = "dd/MM/yyyy";
    public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            var s = reader.GetString();
            if (DateTime.TryParseExact(s, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dt))
            {
                return dt;
            }
            // 解析失败可以按业务逻辑处理,不要调用reader.GetDateTime()
            throw new FormatException($"日期格式不正确,要求格式为{DateFormat}");
        }
        throw new FormatException("日期类型必须为字符串格式");
    }

    public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
    {
        // 按要求格式输出
        writer.WriteStringValue(value.ToString(DateFormat, CultureInfo.InvariantCulture));
    }
}

// 可空类型的转换器同理修改Write方法和解析失败的逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:54:02