Created
September 11, 2018 09:51
-
-
Save MovGP0/ddcc9eb15d1527b50fba1706af6d8914 to your computer and use it in GitHub Desktop.
Configure NodaTime for NewtonSoft.Json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using NodaTime.Serialization.JsonNet; | |
namespace MyApp | |
{ | |
public sealed class Startup | |
{ | |
public Startup(IHostingEnvironment env, IConfiguration configuration) | |
{ | |
Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); | |
HostingEnvironment = env ?? throw new ArgumentNullException(nameof(configuration)); | |
} | |
public IHostingEnvironment HostingEnvironment { get; } | |
public IConfiguration Configuration { get; } | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
// ... | |
JsonConvert.DefaultSettings = () => new JsonSerializerSettings | |
{ | |
Formatting = hostingEnvironment.IsProduction() ? Formatting.None : Formatting.Indented, | |
DateFormatHandling = DateFormatHandling.IsoDateFormat, | |
DateTimeZoneHandling = DateTimeZoneHandling.Local | |
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); | |
services.AddMvc().AddJsonOptions(options => | |
{ | |
options.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); | |
options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; | |
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; | |
options.SerializerSettings.Formatting = hostingEnvironment.IsProduction() ? Formatting.None : Formatting.Indented; | |
}); | |
// ... | |
} | |
public void Configure(IApplicationBuilder app, IHostingEnvironment env) | |
{ | |
// ... | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment