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

在C# .NET Core Web API中如何给datetime字段传入空字符串

在.NET Core Web API中处理DateTime字段的空字符串输入

问题场景

当你向.NET Core Web API的Nullable<DateTime>类型字段传入空字符串时,会触发JSON转换错误,示例请求和错误如下:

请求JSON:

{
    "isCompany": null,
    "Loans2020": {
        "dateOf": "2022-12-31T19:00:00.000Z",
        "Amount": 1000
    },
    "Loans2021": {
        "Amount": 0,
        "dateOf": ""
    }
}

返回错误:

"errors": {
    "request": [
      "The request field is required."
    ],
    "$.Loans2021.dateOn": [
      "The JSON value could not be converted to System.Nullable`1[System.DateTime]. Path:.."
    ]
}

这是因为默认的System.Text.Json序列化器不支持将空字符串直接转换为DateTime?的null值,需要自定义处理逻辑。


解决方案

方法1:全局配置JSON转换器

在项目的Program.cs中添加全局JSON序列化配置,注册自定义转换器来处理空字符串转DateTime?的逻辑:

var builder = WebApplication.CreateBuilder(args);

// 添加控制器并配置JSON选项
builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new DateTimeNullableConverter());
    });

// 自定义Nullable<DateTime>转换器
public class DateTimeNullableConverter : JsonConverter<DateTime?>
{
    public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        if (reader.TokenType == JsonTokenType.String)
        {
            var strValue = reader.GetString();
            // 空字符串转为null
            if (string.IsNullOrWhiteSpace(strValue))
                return null;
            // 尝试解析有效时间字符串
            if (DateTime.TryParse(strValue, out DateTime result))
                return result;
        }
        // 处理JSON null值
        else if (reader.TokenType == JsonTokenType.Null)
        {
            return null;
        }
        throw new JsonException("无法将JSON值转换为Nullable<DateTime>");
    }

    public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options)
    {
        if (value.HasValue)
            writer.WriteStringValue(value.Value);
        else
            writer.WriteNullValue();
    }
}

var app = builder.Build();

// 其他中间件配置...
app.Run();

方法2:针对单个字段配置转换器

如果不需要全局生效,可直接在模型的目标字段上标注[JsonConverter]特性:

// 贷款模型类
public class LoanDto
{
    public decimal Amount { get; set; }

    // 给单个字段指定转换器
    [JsonConverter(typeof(DateTimeNullableConverter))]
    public DateTime? dateOf { get; set; }
}

// 同样使用方法1中的DateTimeNullableConverter类

方法3:临时字段转换方案

若仅需处理少量字段,可将字段类型改为string,再通过额外属性实现DateTime?的解析:

public class LoanDto
{
    public decimal Amount { get; set; }

    // 接收前端传入的空字符串或时间字符串
    public string? dateOf { get; set; }

    // 供内部逻辑使用的解析后时间(忽略JSON序列化)
    [JsonIgnore]
    public DateTime? ParsedDateOf 
    { 
        get 
        {
            if (string.IsNullOrWhiteSpace(dateOf))
                return null;
            return DateTime.TryParse(dateOf, out DateTime dt) ? dt : null;
        } 
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 02:45:33