I have an Asp.Net WebApi controller with the following action:
public void Post([FromBody]object value)
Now, sometimes this value
parameter is sent as a String
containing a ISO8601-formatted date, and sometimes as a DateTime
. The data is sent in JSON format.
For each of those two options I have to do different things, so I need to make that distinction, but I always end up with a DateTime
value.
I am aware of the fact that my source DateTime
values are being serialized to JSON as strings in ISO8601 format when they are sent to the above action (I am using an HttpClient
for the actual sending), and hence my action cannot differentiate between the two.
My question is whether it is possible to include some kind of type hint to the sent values, in order to tell my WebApi endpoint which specific type is being sent (and enforce that type on the deserialized value
).
Solved this eventually by implementing a custom
JsonConverter
, which serializes string values along with a type hint (similar toNewtonsoft.Json
'sMetadataPropertyHandling
setting inJsonSerializerSettings
).Here is the implementation which does the trick:
And a little usage example: