When creating API’s with .NET Core MVC, you can control the JSON output by adding JsonOptions to the controllers:
public void ConfigureServices(IServiceCollection services) { ... ... services.AddControllers().AddJsonOptions(); ... ... }
This will ensure that when requesting application/json from a GET method, the format returned is JSON.
You can then add Converters to the configuration, controlling the default behavior of the JSON. This is a DateTime converter, forcing any DateTime type to be outputted as “2019-15-09Y22:30:00”
using System.Text.Json; using System.Text.Json.Serialization; namespace MyCode.Converters { public class DateTimeConverter : JsonConverter<DateTime> { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { return DateTime.Parse(reader.GetString()); } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToLocalTime().ToString("yyyy-MM-ddTHH:mm:ss")); } } }
The converter needs to be added to my configuration:
public void ConfigureServices(IServiceCollection services) { ... ... services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new Converters.DateTimeConverter()); } ); ... ... }
MORE TO READ:
- Create Web API’s with ASP.NET Core by Microsoft
- Setting JSON Serialization Configuration At Runtime On A .NET Core API by .NET Core Tutorials
- Try the new System.Text.Json APIs by Immo Landwerth
Yes System.Text.Json is very nice :)
Good post!
LikeLike
This is great, I really like the simplicity, can it convert to a format based on the date type field in the model?
Model:
[DataType(DataType.Date)]
public DateTime PickUpDt { get; set; }
[DataType(DataType.Time)]
public DateTime PickupTm { get; set; }
How might I specify which Converter to apply based on the specified data type (Date or Time).
If it is a DataType.Time I would want to display in date format HH:mm,
LikeLike
Pingback: Handling “415 Unsupported Media Type” in .NET Core API | Brian Pedersen's Sitecore and .NET Blog
This really helped me get out of a bind I was in with some date formatting preventing request body JSON model binding. Thanks for the great post!
LikeLike