日期时间属性没有约束力导致模型为空。 [英] Datetime property is not binding causing the model to be null.
问题描述
我的WebAPI期待一个模型如下图所示:
型号:
公共类为MyModel
{
公众的DateTime日期时间{获得;设置; }
}
WebAction方式:
公共IHttpActionResult邮政([FromBody]为MyModel模型)
我使用 RestSharp
来发送一个请求。
VAR restRequest =新RestRequest(URL,Method.POST)
{
RequestFormat = DataFormat.Json,
}; restRequest.AddBody(新为MyModel {日期时间= DateTime.Now},);
但模型绑定总是空(在的WebAPI侧)。
我看到提琴手如下: {日期时间:2014-09-25T07:22:56.7095909Z}
任何想法,为什么?
最后似乎新JsonMediaTypeFormatter {UseDataContractJsonSerializer =真};
竟然是罪魁祸首。 p>
详情:
在 WebApiConfig
类,我试图让的XmlSerializer
默认的,而不是一个 JsonSerializer
这是默认的在的WebAPI
。
不过,在不知不觉中我已设置 UseDataContractJsonSerializer = TRUE
。这竟然是罪魁祸首。
其实, UseDataContractJsonSerializer
主要用于支持 WCF
序列化。它系列化这是已被标记为 DataContract
模型的所有属性。
这样做的问题是,这种串行预计日期
将在划时代
格式。
在丝,日期和时间属性的作用给予这里
我SO回答这里这本被称为这里这么回答 解释这个更漂亮。
由于我使用的是专为 WCF
串行器,它希望在ASP.NET格式的日期(例如), \\ /日期(1234567890)\\ /。
和注意,的WebAPI
默认的序列化是NewtonSoft JSON序列。详情请阅读这里一>
所以,使用JSON序列在的WebAPI
只是做新JsonMediaTypeFormatter()
孤单。
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 ?
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.
这篇关于日期时间属性没有约束力导致模型为空。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!