2

我向API控制器提交日期值为“02/11/2015”(DD/MM/YYYY)的JSON对象。出于某种原因,它会在绑定(2月11日)时转换为美国格式。我在同一个解决方案中使用了标准的MVC控制器,它将绑定的日期值以相同的格式正确提交(英国)。什么会造成这种差异:ASP.NET Web API日期时间绑定

下面是标准的MVC提交标题:

Accept:*/* 
Accept-Encoding:gzip, deflate 
Accept-Language:en-US,en;q=0.8,pl;q=0.6 
Cache-Control:no-cache 
Connection:keep-alive 
X-Requested-With:XMLHttpRequest 

而且表单数据

StartDate : 01/11/2015 

这里有API调用头

Accept:application/json, text/javascript, */*; q=0.01 
Accept-Encoding:gzip, deflate, sdch 
Accept-Language:en-US,en;q=0.8,pl;q=0.6 
Cache-Control:no-cache 
Connection:keep-alive 
Content-Type:application/json; charset=UTF-8 
X-Requested-With:XMLHttpRequest 

和JSON对象我通过

{ DateStart: "01/11/2015" } 

回答

0

我猜webapi json serializer中的默认dateFormat与MVC的不一样。

尝试在配置文件(App_start/WebApiConfig)中的WebApi中指定。

例子:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter; 
json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; 

或者 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateFormatString = “YYYY-MM-DD”

与日期格式,DateZone需要。

更多的相关信息在这里:

Post dates web api custom format

+0

遗憾的是没有您的解决方案的工作 – Bartosz

+1

'GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateFormatString = “YYYY-MM-DD”'中的登记方法你webapiconfig文件不更改格式? –

+0

使它最终使用自定义转换为DateTime类型:config.Formatters.JsonFormatter.SerializerSettings.Converters.Insert(0,new MyDateTimeConverter());感谢您的帮助 – Bartosz