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

ASP.NET Core 6 Web API DateTime格式验证失败求助

Angular提交DateTime到ASP.NET Core 6 Web API验证失败的解决方法

问题概述

提交dd/MM/yyyy格式的日期字符串到ASP.NET Core后端时,Created字段无法被正确解析为DateTime类型,返回验证错误:

product.Created: ["The value '16/02/2023' is not valid for Created."]

解决方案

方案1:前端转换日期为后端可解析的格式

ASP.NET Core默认能解析ISO 8601格式(如2023-02-16T00:00:00.000Z)或**yyyy-MM-dd**格式的日期,在Angular的提交方法中转换日期格式:

submit(){      
    let product: ProductApi = this.form.value;
    
    // 将 dd/MM/yyyy 转换为 yyyy-MM-dd
    const [day, month, year] = product.created.split('/');
    product.created = `${year}-${month}-${day}`;

    // 或者转换为ISO标准格式(推荐)
    // const dateObj = new Date(`${month}/${day}/${year}`);
    // product.created = dateObj.toISOString();

    let formData = new FormData();
    formData.append('data', this.file);
    
    for (let k in product) {
        formData.append(`product.${k}`, product[k]);            
    }

    this.productApiService.createWithFile(formData).then(
        res => {
            this.result = do something;
        },
        err => {
            console.log(err);                
        }
    );
}

方案2:后端配置全局日期解析规则

如果需要后端直接支持dd/MM/yyyy格式的日期解析,可通过自定义ModelBinder实现全局配置:

  1. 在Program.cs中注册自定义ModelBinder:
builder.Services.AddControllers()
    .AddMvcOptions(options =>
    {
        // 插入自定义日期绑定器到最前面
        options.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
    });
  1. 实现自定义绑定器类:
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Globalization;

public class DateTimeModelBinderProvider : IModelBinderProvider
{
    public IModelBinder? GetBinder(ModelBinderProviderContext context)
    {
        // 为DateTime和可空DateTime类型提供绑定器
        if (context.Metadata.ModelType == typeof(DateTime) || context.Metadata.ModelType == typeof(DateTime?))
        {
            return new DateTimeModelBinder();
        }
        return null;
    }
}

public class DateTimeModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (valueProviderResult == ValueProviderResult.None)
        {
            return Task.CompletedTask;
        }

        bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
        var dateStr = valueProviderResult.FirstValue;

        // 尝试解析dd/MM/yyyy格式的日期
        if (DateTime.TryParseExact(dateStr, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
        {
            bindingContext.Result = ModelBindingResult.Success(date);
        }
        else
        {
            // 解析失败时添加错误信息
            bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "日期格式无效,请使用dd/MM/yyyy格式");
        }

        return Task.CompletedTask;
    }
}

方案3:为单个字段配置绑定规则

如果仅需要特定字段支持dd/MM/yyyy格式,可直接在实体类字段上指定绑定器:

using Microsoft.AspNetCore.Mvc;

public partial class Product
{
    // 其他字段...

    [BindProperty(BinderType = typeof(DateTimeModelBinder))]
    public DateTime Created { get; set; }  

    // 其他字段...
}

为什么之前的DisplayFormat特性无效?

[DisplayFormat]和[DataType(DataType.Date)]主要用于视图层的显示和编辑模板,不会影响ASP.NET Core的ModelBinding解析逻辑。ModelBinding默认使用当前请求文化的日期格式或ISO标准格式,因此需要通过自定义绑定器或全局配置来支持非标准日期格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:57:38