質問

When I post a json object with a date property to a ApiController it won't deserialize into a date.

Server site code:

public class MegaTestController : ApiController
{
    // POST /megatest
    public void Post(ttt value)
    {
        string sdf = "!sad";
    }
}

public class ttt
{
    public DateTime Date { get; set; }
    public string Name { get; set; }
}

Then I do a POST request with fiddler

POST http://localhost:62990/MegaTest HTTP/1.1

User-Agent: Fiddler

Host: localhost:62990

Content-Type: text/json

Content-Length: 54

{ "Date":"/Date(1239018869048)/", "Name":"Dude" }

But the object coming in only has the Name property set, the Date property is {01.01.0001 00:00:00}

Am I missing any headers or project settings?


Edit: The requests are actually coming from a HttpClient. Is it possible to format the date before sending the request over with HttpClient?

public Task<T> Create<T>(T item)
{
    var service = new HttpClient();
    service.BaseAddress = new Uri("http://localhost:62990");

    var method = typeof(T).Name + "s"; // in this case it will be ttts

    var req = new HttpRequestMessage<T>(item);
    req.Content.Headers.ContentType = new MediaTypeHeaderValue("text/json");

    return service.PostAsync(method, req.Content).ContinueWith((reslutTask) =>
    {
        return reslutTask.Result.Content.ReadAsAsync<T>();
    }).Unwrap();
}

var data = new ttt { Name = "Dude", Date = DateTime.Now };
Create(data);

Edit: This is a known bug with the ASP MVC 4 Beta and the final version of ASP MVC 4 will use Json.net as a json serializer until then you can use the default XML serializer or switch out the default Json serializer for Json.net. More info can be found on hanselman blog

正しい解決策はありません

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top