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

如何处理Web API输入请求中的JSON Date格式问题

JSON Date格式在Web API中的解析解决方案

你的问题本质是.NET Web API默认的JSON序列化器对微软旧版/Date(时间戳)/格式的日期支持不足,导致模型绑定失败,请求对象字段被设为null;而ISO标准的yyyy-MM-dd格式是序列化器默认支持的,所以能正常解析。以下分两种常用序列化场景给出解决办法:

场景1:使用Newtonsoft.Json(Json.NET)作为序列化器

如果你的项目是传统ASP.NET Web API,或是ASP.NET Core中手动配置了Json.NET:

  1. 确保已安装Newtonsoft.Json(ASP.NET Core需额外安装Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet包)
  2. 在配置中开启对旧版JSON Date格式的解析:
    // ASP.NET Core(Program.cs)
    builder.Services.AddControllers()
        .AddNewtonsoftJson(options =>
        {
            // 开启自动解析/Date(xxxx)/格式
            options.SerializerSettings.DateParseHandling = DateParseHandling.DateTime;
            // 根据业务需求设置时区,可选Local或Utc
            options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
        });
    
    // 传统ASP.NET Web API(Global.asax.cs)
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateParseHandling = DateParseHandling.DateTime;
    GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
    

场景2:使用System.Text.Json(ASP.NET Core默认序列化器)

System.Text.Json默认不支持/Date(xxxx)/格式,需要自定义转换器来兼容:

  1. 创建自定义日期转换器类:

    using System;
    using System.Text.Json;
    using System.Text.Json.Serialization;
    using System.Text.RegularExpressions;
    
    public class JsonNetDateConverter : JsonConverter<DateTime>
    {
        private static readonly Regex _jsonNetDateRegex = new Regex(@"\/Date(\d+)\/", RegexOptions.Compiled);
    
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var dateStr = reader.GetString();
            if (string.IsNullOrWhiteSpace(dateStr))
                return default;
    
            // 匹配并解析/Date(时间戳)/格式
            var match = _jsonNetDateRegex.Match(dateStr);
            if (match.Success && long.TryParse(match.Groups[1].Value, out var timestamp))
            {
                return DateTimeOffset.FromUnixTimeMilliseconds(timestamp).LocalDateTime;
                // 若需UTC时间,替换为:return DateTimeOffset.FromUnixTimeMilliseconds(timestamp).UtcDateTime;
            }
    
            // 兼容ISO格式解析
            if (DateTime.TryParse(dateStr, out var dateTime))
                return dateTime;
    
            throw new JsonException($"无法解析日期字符串:{dateStr}");
        }
    
        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            // 如需输出/Date(xxxx)/格式,保留以下代码;否则注释掉,用默认ISO格式输出
            var timestamp = new DateTimeOffset(value).ToUnixTimeMilliseconds();
            writer.WriteStringValue($"/Date({timestamp})/");
        }
    }
    
  2. 在配置中注册转换器:

    // Program.cs
    builder.Services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new JsonNetDateConverter());
        });
    

额外检查项

  • 确保Postman请求的Content-Type头设置为application/json
  • 若你的日期字段是可空类型(DateTime?),需将转换器修改为继承JsonConverter<DateTime?>,并调整Read方法的返回逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 02:35:21