在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.声明一个时间戳转换器 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.配置使用时间戳转换器(到这一步API就能序列化和反序列化时间戳了) 1 public static class WebApiConfig 2 { 3 public static void Register(HttpConfiguration config) 4 { 5 //启用标记路由功能 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 //设置Datetime 到 時間戳 的互轉 16 JsonSerializerSettings jSettings = new Newtonsoft.Json.JsonSerializerSettings() 17 { 18 Formatting = Formatting.Indented, 19 DateTimeZoneHandling = DateTimeZoneHandling.Local 20 }; 21 jSettings.Converters.Add(new UnixDateTimeConvertor()); 22 config.Formatters.JsonFormatter.SerializerSettings = jSettings; 23 24 } 25 }
3.因为项目中使用了Swagger UI自动生成WebApi文档如果想接口文档Datetime显示的Example是时间戳可以如以下设置,在你自己的SwaggerConfig设置中添加Datetime及Datetime?的映射和默认值 1 config 2 .EnableSwagger(c => 3 { 4 //...省略无关代码 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 }); 最终生成的Webapi文档显示如下
|
请发表评论