I have the following code for model:
public class Sensor
{
public long Id { get; set; }
[Required]
public string Tag { get; set; }
public DateTime Timestamp { get; set; }
public string Status { get; set; }
public int Valor { get; set; }
}
I am receiving this by an WebAPI Controller, by POST method.
This is the signature for the POST method:
public async Task<ActionResult<Sensor>> PostSensor(Sensor sensor)
It receives values like this example:
{
"tag": "mytag",
"Timestamp": "1575179924",
"valor": "3000"
}
My problem is that due to the Controller's signature, it tries to validate the timestamp, and fails because the UNIX Timestamp isn't the DateTime one.
I wanted to convert it inside this method, but this would require disabling validation for the whole Controller.
I tried creating a JSON Converter, but it always fails to convert.
public class UnixEpochTimeToDateTimeConverter: Newtonsoft.Json.JsonConverter
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (!reader.Path.ToLower().Contains("time")) return null;
var parsed = long.TryParse(reader.Value.ToString(), out var unixTimeStamp);
if(!parsed){ return null; }
var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var timeSpan = TimeSpan.FromSeconds(unixTimeStamp);
var localDateTime = epoch.Add(timeSpan).ToLocalTime();
return localDateTime;
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}
(I get this error: The JSON value could not be converted to System.DateTime. Path: $.Timestamp)
Is there a solution for this? Maybe another way to convert it? (I really don't know if i am doing anything wrong)