为Web api中的模型指定绑定日期属性的日期格式

问题描述 投票:0回答:1

我的api中有一个包含id和DateTime属性的类。

public class MyTestClass
    {
        public int id { get; set; }
        public DateTime dateTime { get; set; }

    }

我想知道是否有一种方法只能接受具有特定日期格式的JSON字符串。我的问题是模型联编程序将同时解析“ 21-01-1991”和“ 01-21-1991”。

示例API控制器

public void Post(MyTestClass myTest)
        {
            DateTime x = myTest.dateTime;
        }

如果用户以iso 8601格式以外的任何其他格式发送dateTime属性,我希望api返回错误的请求。

c# api datetime model-binding
1个回答
0
投票

[暂时不要因为“模型绑定”和“全局设置”而分心,让我们看一个非常简单的解决方案。

将一些常量设置为您期望字符串采用的格式。反序列化数据并将JSON值存储为字符串。不要试图强制源字符串数据采用任何特定的日期格式,ISO或其他格式。然后,在需要时,使用get属性将数据解析为DateTime对象。

public class MyTestClass
{
    public const string DATETIME_FORMAT = "MM-DD-YYYY";
    public int id { get; set; }
    public string dateTime { get; set; }
    public DateTime dateTimeConverted
    {
        get
        {
            string[] parts = dateTime.Split('-');
            int year, month, day;

            if (DATETIME_FORMAT == "MM-DD-YYYY")
            {
                year = Int32.Parse(parts[2]);
                month = Int32.Parse(parts[0]);
                day = Int32.Parse(parts[1]);   
            }
            else if (DATETIME_FORMAT == "DD-MM-YYYY")
            {
                year = Int32.Parse(parts[2]);
                month = Int32.Parse(parts[1]);
                day = Int32.Parse(parts[0]); 
            }

            return new DateTime(year, month, day);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.