Asp.net webapi Datetime serialization \ deserialization is a timestamp, webapidatetime
For project requirements, Datetime serialization and deserialization timestamp (long) in Webapi must be implemented. If you encounter the same problem, you can refer to it.
1. Declare a timestamp Converter
1 public class UnixDateTimeConvertor : DateTimeConverterBase 2 { 3 4 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 5 { 6 long jsTimeStamp = long.Parse(reader.Value.ToString()); 7 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 8 DateTime dt = startTime.AddMilliseconds(jsTimeStamp); 9 return dt;10 }11 12 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)13 {14 System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); 15 long timeStamp = (long)(((DateTime)value) - startTime).TotalMilliseconds; 16 writer.WriteValue(timeStamp);17 }18 }
2. Configure the timestamp converter (by this step, the API can serialize and deserialize the timestamp)
1 public static class WebApiConfig 2 {3 public static void Register (HttpConfiguration config) 4 {5 // enable the flag routing function 6 config. mapHttpAttributeRoutes (); 7 8 config. routes. mapHttpRoute (9 name: "DefaultApi", 10 routeTemplate: "api/{controller}/{id}", 11 defaults: new {id = RouteParameter. optional} 12); 13 15 // set the time stamp from Datetime to 16 16 JsonSerializerSettings jSettings = new Newtonsoft. json. jsonSerializerSettings () 17 {18 Formatting = Formatting. indented, 19 DateTimeZoneHandling = DateTimeZoneHandling. local20}; 21 jSettings. converters. add (new UnixDateTimeConvertor (); 22 config. formatters. jsonFormatter. serializerSettings = jSettings; 23 24} 25}
3. because the project uses Swagger UI to automatically generate WebApi documentation. If you want to use the interface documentation Datetime to display Example as a timestamp, you can add Datetime and Datetime in your own SwaggerConfig settings? Ing and default value
1 config 2. enableSwagger (c => 3 {4 //... omit irrelevant Code 5 6 System. dateTime startTime = TimeZone. currentTimeZone. toLocalTime (new System. dateTime (1970, 1, 1); 7 long exampleVal = (long) (DateTime. now-startTime ). totalMilliseconds; 8 Schema timeSchema = new Schema {type = "number", format = "long", example = exampleVal}; 9 10 c. mapType <DateTime?> () => TimeSchema); 11 c. MapType <DateTime> () => timeSchema); 12 13 });
The generated Webapi document is shown as follows: