Here is a simplified version of the model I have to work with:
class InputModel
{
public string Name { get; set; }
public object Value { get; set; }
}
And the relevant parts of the controller:
class Controller : ApiController
{
[HttpPut]
public async Task<IHttpActionResult> Update([FromBody]InputModel model)
{
//implementation
}
}
the Value property of the InputModel class could be of any type, and which type it will be is only known later on, in a piece of legacy code the model is sent to and that i have no control over.
The problem I have occurs with the following json in the request body:
{
"name": "X",
"value": "2001-10-17T13:55:11.123"
}
The default behavior is to parse this json so that the Value property gets converted to a DateTime. DateTimes however are handled very differently from strings in the legacy code and data is lost after handling it (for example: the millisecond part is removed when persisting to the database). So when the same value is later requested, the returned value is "2001-10-17T13:55:11" (milliseconds missing).
Of course I can fix this by globally setting this in my web api configuration:
httpConfiguration.Formatters.JsonFormatter.SerializationSettings.DateParseHandling = DateParseHandling.None;
But doing so disables parsing DateTimes also for models in other methods and controllers that have models for which the default behavior is wanted.
What I'm looking for is something like the following (imaginary) code:
class InputModel
{
public string Name { get; set; }
[JsonSerializerSettings(DateParseHandling = DateParseHandling.None)]
public object Value { get; set; }
}
But I can't find out how to achieve this. Any help would be greatly appreciated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…