1.WebApiConfig
config.Formatters.JsonFormatter.SerializerSettings.Converters.Insert( 0, new JsonDateTimeConverter());
public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.EnableCors(new EnableCorsAttribute("*", "*", "*")); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SerializerSettings.Converters.Insert( 0, new JsonDateTimeConverter()); } }
2.JsonDateTimeConverter类
/// <summary> /// Json日期带T格式转换 /// </summary> public class JsonDateTimeConverter : IsoDateTimeConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { DateTime dataTime; if (DateTime.TryParse(reader.Value.ToString(), out dataTime)) { return dataTime; } else { return existingValue; } } public JsonDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; } }
3.因为我是自定义统一返回格式 所以需要引用下全局的 JsonMediaTypeFormatter jtye = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
public class ResponseJsonResult : IHttpActionResult { object _value; HttpRequestMessage _request; public ResponseJsonResult(object value, HttpRequestMessage request) { _value = value; _request = request; } public Task<HttpResponseMessage> ExecuteAsync(System.Threading.CancellationToken cancellationToken) { JsonMediaTypeFormatter jtye = GlobalConfiguration.Configuration.Formatters.JsonFormatter; var response = new HttpResponseMessage() { Content = new ObjectContent(typeof(object), _value, jtye), RequestMessage = _request }; return Task.FromResult(response); } }
4.使用
var oData = new { code = 200, msg = "获取数据成功", total = totalRecord, data = carshoplist }; return new ResponseJsonResult(oData, this.Request);
标签:webapi,asp,c#,JsonDateTimeConverter,object,value,new,config,public From: https://www.cnblogs.com/linyijia/p/16925144.html