简体   繁体   中英

Assigning date field from dynamic context to string value in C#

I have come across this scenario where an API call is done from an angular service.

From angular Service:
    param = {
        date:"2018-10-10T17:03:38.000Z",
        id:"1234"
    }
    //...
    this.http.post(url, param).map(res => res.json()) // call to an MVC API

//MVC API
[HttpPost]
public IHttpActionResult UpdateDate(dynamic context)
{
   string id = context.id;   //stores value as is
   string isoDate = context.date; 
   // iso formatted date string converts back to the following format
   //"10/10/2018 15:20:55"
}

isoDate field now have "10/10/2018 15:20:55" instead of original value "2018-10-10T17:03:38.000Z"

Any idea?

I came up with the work around is pass the date with suffix and prefix as follows "|2018-10-10T17:03:38.000Z|" and replaced "|" with empty string once the value of isoDate is assigned. This seems to be a hack still but works.

Just wanted to know the inside why this happens. Thank you.

The only real primitive types in json are strings , numbers , and booleans so conversion to dynamic ( expando object ) can be done only for those types. Everything else passed in as string (like your ISO8601 formatted date time) stays as string .

If you want conversion to a DateTime you would have to use a strongly typed model so that the deserializer ( json.net by default for web-api ) will attempt to parse the incoming string value to a DateTime type. Using a strong typed model is recommended as there is less chance of naming errors at run time ( because you would catch those at compile time ) and you can validate the model with model validation annotations like RequiredAttribute .

See also JSON Data Types

I encounter the same error today.

Inspecting the property of the dynamic object that contains the ISO string date, I saw that it was already converted to an object that contained a Value property that was a Date object (somne implicit conversion takes place, that's for sure).

在此处输入图片说明

In the image, parametros is a dynamic object and dataPartida the property that was a ISO date string sent as a POST body payload from Postman.

To solve my problem, I did:

string dataPartida = parametros["dataPartida"].Value.ToString("yyyy-MM-dd'T'HH:mm:ss");

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM