問題:因為使用的是ABP3.9以上版本,利用網上的修改返回json的時間格式 不是無效就是在提交表單時時間格式被驗證無效
1、說明:ABP的json轉換主要是利用Newtonsoft.Json來進行,WebApi的表單提交與控制器方法的返回的json的是經過ReadJson和WriteJson
2、創建MyAbpCamelCasePropertyNamesContractResolver繼承AbpCamelCasePropertyNamesContractResolver
3、創建MyAbpDateTimeConverter繼承AbpDateTimeConverter
具體代碼如下:
1、新建MyAbpDateTimeConverter

1 public class MyAbpDateTimeConverter : AbpDateTimeConverter 2 { 3 public override bool CanConvert(Type objectType) 4 { 5 return objectType == typeof(DateTime) || objectType == typeof(DateTime?); 6 } 7 8 public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 9 { 10 //DateTime.ParseExact(reader.Value.ToString(),"yyyy-MM-dd HH:mm:ss",(IFormatProvider)this.Culture, DateTimeStyles.RoundtripKind); 11 this.DateTimeFormat = ""; 12 DateTime? nullable = base.ReadJson(reader, objectType, existingValue, serializer) as DateTime?; 13 if (nullable.HasValue) 14 return (object)Clock.Normalize(nullable.Value); 15 return (object)null; 16 } 17 18 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 19 { 20 DateTime? nullable = value as DateTime?; 21 base.WriteJson(writer, nullable.HasValue ? (object)Clock.Normalize(nullable.Value) : value, serializer); 22 } 23 }
2、新建MyAbpCamelCasePropertyNamesContractResolver
public class MyAbpCamelCasePropertyNamesContractResolver: AbpCamelCasePropertyNamesContractResolver { protected override void ModifyProperty(MemberInfo member, JsonProperty property) { base.ModifyProperty(member, property); if (property.Converter is IsoDateTimeConverter) { property.Converter = new MyAbpDateTimeConverter() { DateTimeFormat= "yyyy-MM-dd HH:mm:ss" }; } } }
3、在ABP中WebApiModule模塊中重寫PostInitialize()
public override void PostInitialize() { base.PostInitialize(); Configuration.Modules.AbpWebApi().HttpConfiguration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new MyAbpCamelCasePropertyNamesContractResolver(); }