Datetime property is not binding causing the model

2019-09-17 21:03发布

问题:

My WebAPI is expecting a model like below:

Model:

public class MyModel 
{
  public DateTime datetime {get;set; }
}

WebAction Method:

public IHttpActionResult Post([FromBody] MyModel model)

I am using RestSharp to send a request.

            var restRequest = new RestRequest(url, Method.POST)
            {
                RequestFormat = DataFormat.Json,
            };

            restRequest.AddBody(new MyModel {Datetime =DateTime.Now}, ""); 

But the model binding is always null (in the webapi side).

I see the following in Fiddler: {"datetime":"2014-09-25T07:22:56.7095909Z}"

Any ideas why ?

回答1:

Change the request to:

restRequest.AddBody(new MyModel { datetime =DateTime.Now}, "");

In Fiddler, you want to be seeing this:

{"datetime":"2014-09-25T07:22:56.7095909Z}"

Since that will match the name of the property in your class:

public DateTime datetime {get;set; }

Model binding should then be able to pick that up from the request and, using reflection, find a property named "datetime" in a MyType instance and set a value to it.



回答2:

Finally seems the new JsonMediaTypeFormatter {UseDataContractJsonSerializer = true}; turned out to be the culprit.

In Detail:

At WebApiConfig class, I have tried to make the XmlSerializer the default one instead of JsonSerializer which is the default one in WebApi.

But unknowingly I have set UseDataContractJsonSerializer = true. This turned out to be the culprit.

Actually, UseDataContractJsonSerializer is primarily used to support WCF serialization. It serializes all the model properties which is has been marked as DataContract.

The problem with this is , this serializer expects the date to be in epoch format.

In the wire, the date time property behaves as given here.

I referred this in SO answer here and this SO answer here explains this even more beautifully.

Since I was using a serializer that is designed for WCF, it expects the date in the ASP.NET format (e.g.), \/Date(1234567890)\/.

And note that the default serializer in WebAPI is NewtonSoft Json Serializer. Read more in here

So, to use a Json serializer in WebApi just do new JsonMediaTypeFormatter() alone.