I have a WebAPI set up which is accepting JSON, using the Newtonsoft.Json package, where one of the fields is a DateTime.
In order to avoid problems with invalid or ambiguous date formats, I only want to accept specific date formats on the input.
For example, only accept:
var validFormats = new string[]
{
"yyyy-MM-ddTHH:mm:ss", // 2009-06-15T13:45:30
"yyyy-MM-ddTHH:mm:ss.fffffffzz", // 2009-06-15T13:45:30.0000000-07:00
};
The problem I am having is that wherever I try to do any manual format validation or parsing, it seems that the parser has already deserialised and converted the string to a DateTime object, so I cannot get hold of the date in the original format to check.
What is the best way to accomplish this?
Update 1:
The closest I have come is to use a custom converter:
public class JsonDateTimeConverter : DateTimeConverterBase
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var validFormats = new string[]
{
"yyyy-MM-ddTHH:mm:ss", // 2009-06-15T13:45:30
"yyyy-MM-ddTHH:mm:ss.fffffffzz", // 2009-06-15T13:45:30.0000000-07:00
};
DateTime dt;
if (DateTime.TryParseExact(reader.Value.ToString(), validFormats, null, DateTimeStyles.None, out dt))
{
return dt;
}
throw new JsonException("Failed to parse DateTime");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((DateTime)value).ToString("o"));
}
}
Configured to be used in the WebApiConfig as
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new JsonDateTimeConverter());
But this still has the issue where the reader.value appears to already have been converted to a DateTime object. There is a private member on JsonReader called _stringReference which appears to contain the original string, but I am unable to access this in within the converter.