当具有TimeSpan属性时,从body获取对象会返回错误的属性值

时间:2016-10-06 14:09:34

标签: asp.net json asp.net-web-api

我的ASP.NET Web API控制器方法采用自定义对象:

[HttpPost, Route("...{id}...")]
public async Task<long> Post(long id, Timesheet timesheet) {
    ... //only one of timesheet's properties are properly set, the DateTime
    return result;
}

这是Timesheet类(混淆,抱歉):

public class Timesheet
{
    //This DateTime is the only property that gets converted properly
    public DateTime a { get; set; } 
    public int b { get; set; }
    public string c { get; set; }
    public TimeSpan d { get; set; } //System.Timespan
    public TimeSpan e { get; set; }
    public string f { get; set; }
    public long g { get; set; }
    public int h { get; set; }
}

当我从类中删除两个TimeSpan属性时,所有属性都已正确转换。我使用默认格式化程序/转换器,并且我收到的信息为application/json。我使用ASP.NET Web API 5.2.3.NET Framework 4.5.2

当我发送(从客户端)和接收(在客户端中)TimeSpan时,它都会获得格式"d":"07:30:00",这应该是正确的。 Newtonsoft.Json无论如何都同意。因此,当我从API发送到客户端时,它会被序列化并反序列化。但是,当我从客户端直接序列化它时,它没有通过默认格式化程序/转换/无论它是否正确反序列化。

这是一个错误吗?

我目前没有时间对其进行进一步测试,但我的快速解决方法是通过System.Net.Http.HttpRequestMessageNewtonsoft.Json.JsonConvert(6.0.4)手动转换它:

[HttpPost, Route("...{id}...")]
public async Task<long> Post(long id, HttpRequestMessage req)
{
    var response = await Request.Content.ReadAsStringAsync();
    var timesheet = JsonConvert.DeserializeObject<Timesheet>(response);
    ...
    return result;
}

0 个答案:

没有答案