web api 2 无法获得正确的日期值

web api 2 can't get correct date value

当我试图从 post 方法获取对象时,我无法获取 DateTime 的正确值,我的 JSON:

{
        "JobRecord": [{
            "ShiftRecordID": 2,
            "JobDescriptionID": 0,
            "TaskDesciption": "Test task description",
            "WorkedWith": "I,G",
            "StartTime": "2015-02-06T07:30:00",
            "EndTime": "2015-02-06T09:00:00",
            "JobDescription": "Exit & Emergency Remedials",
            "JobNumber": 11939
        }],
    "EmployeeID": 1,
    "isCompanyCar": false
}

StartTime 和 EndTime 的值总是变成 0001/01/01 00:00:00,谁知道问题出在哪里?我在这里呆了 2 天,找不到任何相关的解决方案。

Class定义

public class JobRecordJson
{
    public int JobDescriptionID { get; set; }
    public string TaskDescription { get; set; }
    public string WorkedWith { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime EndTime { get; set; }
    public int EmployeeID { get; set; }
    public bool IsCompanyCar { get; set; }
    public DayType DayType { get; set; }
}

控制器

[ResponseType(typeof(JobRecord))]
    public IHttpActionResult PostJobRecord(JobRecordJson jobRecord)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        Debug.WriteLine(jobRecord);
        //DateTime.Parse(jobRecord.StartTime);
        // check if a shift record was created
        var shiftRecord = from r in db.ShiftRecords
                          where r.RecordDate == jobRecord.StartTime.Date && r.EmployeeID == jobRecord.EmployeeID
                          select r;
        try
        {
            int shiftRecordID;
            // if there isn't, create shift record first
            if (shiftRecord.Count() < 1)
            {

                int maxRecordID = db.ShiftRecords.Max(m => m.ID);
                ShiftRecord sr = new ShiftRecord()
                {
                    ID = maxRecordID + 1,
                    EmployeeID = jobRecord.EmployeeID,
                    IsCompanyVehicle = jobRecord.IsCompanyCar,
                    RecordDate = jobRecord.StartTime.Date,
                    DayType = jobRecord.DayType,
                    IsRead = false
                };
                db.ShiftRecords.Add(sr);
                db.SaveChanges();
                shiftRecordID = sr.ID;
            }
            else 
            {
                shiftRecordID = shiftRecord.First().ID;
            }
            // create job record
            int maxJobRecordID = db.JobRecords.Max(m => m.ID);
            JobRecord jr = new JobRecord()
            {
                ID = maxJobRecordID + 1,
                ShiftRecordID = shiftRecordID,
                JobDescriptionID = jobRecord.JobDescriptionID,
                TaskDesciption = jobRecord.TaskDescription,
                WorkedWith = jobRecord.WorkedWith,
                StartTime = jobRecord.StartTime,
                EndTime = jobRecord.EndTime,
            };
            db.JobRecords.Add(jr);
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            Debug.WriteLine("There is an error: " + ex.ToString());
            return InternalServerError();
        }

        return Ok(jobRecord);
    }

因为我想在不存在任何 ShiftRecord 的情况下自动创建 ShiftRecord,所以我创建了一个 class JobRecordJson(它是一个 DTO class,基本上包含一个 JobRecord class以及我需要的一些额外信息)。 获得 JobRecordJson 对象后,我将创建 JobRecord 项和 ShiftRecord(如果需要)

public class JobRecord
{
    public int ID { get; set; }
    public int JobDescriptionID { get; set; }
    public int ShiftRecordID { get; set; }
    [Display(Name="Task")]
    public string TaskDesciption { get; set; }

    [Display(Name="Worked With")]
    public string WorkedWith { get; set; }

    [Display(Name="Start Time")]
    public DateTime StartTime { get; set; }

    [Display(Name="End Time")]
    public DateTime EndTime { get; set; }
    public virtual JobDescription JobDescription { get; set; }
    public virtual ShiftRecord ShiftRecord { get; set; }
}

public class ShiftRecord
{
    public int ID { get; set; }
    public int EmployeeID { get; set; }

    [Display(Name = "Vehicle Type")]
    public bool IsCompanyVehicle { get; set; }

    [DataType(DataType.Date)]
    [Display(Name = "Date")]
    [DisplayFormat(DataFormatString="{0:yyyy-MM-dd}", ApplyFormatInEditMode=true)]
    public DateTime RecordDate { get; set; }

    [Display(Name="Day Type")]
    public DayType? DayType { get; set; }

    // properties below can only be operated by administrator
    [Display(Name = "Normal Hrs")]
    public decimal? NormalHours { get; set; }

    [Display(Name = "Time And Half Hrs")]
    public decimal? TimeAndHalfHours { get; set; }

    [Display(Name = "Double Time Hrs")]
    public decimal? DoubleTimeHours { get; set; }

    [Display(Name = "Shift Hrs")]
    public decimal? ShiftHours { get; set; }

    [Display(Name="Comment")]
    public string Comment { get; set; }

    [Display(Name="Read?")]
    public bool IsRead { get; set; }
    public virtual Employee Employee { get; set; }
    public virtual ICollection<JobRecord> JobRecords { get; set; }
}

我想这可能是你的 Json。您可以尝试将 属性 名称设置为驼峰式吗?或者甚至更好地创建一个网络 api 方法 returns 您的对象的一个​​示例,然后看看它会给您带来什么。

可能的原因 属性 的大小写不正确: 示例 "startTime":“2015-02-06...”而不是 "StartTime"。这可能就是为什么所有值都为空的原因。

如果您在 post 中看到一个空对象,您的结构可能无效,据我所知,您的 Json 应该开始:

{ ... "startTime":"2015.... }

问题出在您的 json 数据结构上,默认模型绑定器无法将该结构绑定到 JobRecordJson。 您需要定义自己的自定义模型绑定器或将 json 更改为如下内容:

{
  "ShiftRecordID": 2,
  "JobDescriptionID": 12,
  "TaskDesciption": "Test task description",
  "WorkedWith": "I,G",
  "StartTime": "2015-02-06T07:30:00",
  "EndTime": "2015-02-06T09:00:00",
  "JobDescription": "Exit & Emergency Remedials",
  "JobNumber": 11939,
  "EmployeeID": 1,
  "isCompanyCar": false
}