Correct way to post dates to Web API?

三世轮回 提交于 2020-01-15 06:56:07

问题


I am reading data from Web API and populate a form. When I submit it back to Web API, I get this error:

{"Message":"An error has occurred.","ExceptionMessage":"Property 'StartDate' on type 'MvcApplication1.Models.ProductSale' is invalid. Value-typed properties marked as [Required] must also be marked with [DataMember(IsRequired=true)] to be recognized as required. Consider attributing the declaring type with [DataContract] and the property with [DataMember(IsRequired=true)].","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Validation.Validators.ErrorModelValidator.Validate(ModelMetadata metadata, Object container)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ShallowValidate(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n
at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateProperties(ModelMetadata metadata, ValidationContext validationContext)\r\n at System.Web.Http.Validation.DefaultBodyModelValidator.ValidateNodeAndChildren(ModelMetadata metadata, ValidationContext validationContext, Object container)\r\n
at System.Web.Http.ModelBinding.FormatterParameterBinding.<>c_DisplayClass1.b_0(Object model)\r\n at System.Threading.Tasks.TaskHelpersExtensions.<>c_DisplayClass49.b_48()\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"} 1

My date comes Web API as "2013-01-31T16:27:18.503" and posts back as "2013-01-31T05:00:00.000Z". I can intercept the payload before sending to Web API and can use something like http://momentjs.com to parse it, but what should I do? This is driving me nuts!


回答1:


2013-01-31T16:27:18.503 is an XML Date according to XML spec.

2013-01-31T05:00:00.000Z seems to be ISO 8601 date.

Somewhere this seems to be going wrong. Without knowing about your formatters, what you do on date and how it changes impossible to say.

Date format depends on your formatter. If you use a JSON formatter, this could work differently.




回答2:


The error message has the answer. There is nothing wrong with the data that you are posting. Just put the DataMember(IsRequired=true) attribute on your ProductSales's StartDate property to make validation happy.



来源:https://stackoverflow.com/questions/14630794/correct-way-to-post-dates-to-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!