gipasoft

WebApi: Custom DateTime Formatter

Oct 21st, 2019
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1.     public static class WebApiConfig
  2.     {
  3.         public static void Register(HttpConfiguration config)
  4.         {
  5.             // Web API configuration and services
  6.             var json = config.Formatters.JsonFormatter;
  7.             json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
  8.  
  9.             var jsonFormatter = config.Formatters.JsonFormatter;
  10.             var jSettings = new JsonSerializerSettings        
  11.             {
  12.                 Formatting = Formatting.Indented,
  13.                 DateTimeZoneHandling = DateTimeZoneHandling.Utc
  14.             };
  15.             jSettings.Converters.Add(new DateTimeConvertor());
  16.             jsonFormatter.SerializerSettings = jSettings;
  17.  
  18.             config.Formatters.Remove(config.Formatters.XmlFormatter);
  19.             config.Filters.Add(new BasicAuthenticatorFilter("Mondino"));
  20.  
  21.             config.MapHttpAttributeRoutes();
  22.  
  23.             config.Routes.MapHttpRoute(
  24.                 name: "DefaultApi",
  25.                 routeTemplate: "api/{controller}/{id}",
  26.                 defaults: new { id = RouteParameter.Optional }
  27.             );
  28.         }
  29.     }
  30.  
  31.     public class DateTimeConvertor : DateTimeConverterBase
  32.     {
  33.         public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  34.         {
  35.             return DateTime.Parse(reader.Value.ToString());
  36.         }
  37.  
  38.         public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  39.         {
  40.             writer.WriteValue(((DateTime)value).ToIsoDate());
  41.         }
  42.     }
Advertisement
Add Comment
Please, Sign In to add comment