I have following code inside Startup.cs and expecting it to override default serialization options. I want it to override every single serialization throughout my asp net core 2.0 project, but action return value that is not correct, I think this global property is not working in core 2.0
I have it written inside Configure exactly before app.UseMvc();
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
TypeNameHandling = TypeNameHandling.Objects,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
By default, Newtonsoft. Json does case insensitive property name matching during deserialization whereas System. Text. Json does case sensitive matching (with exception in ASP.Net core where you don't need to do anything to achieve behavior like Newtonsoft.
Json library is included in the runtime for . NET Core 3.1 and later versions. For other target frameworks, install the System.
Yet Newtonsoft. Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System. Text.
Json.net is made by newtonsoft.
In ASP.NET Core, this is configured when wiring up the services on the application in Startup.ConfigureServices
. There is an fluent AddJsonOptions(Action<MvcJsonOptions>)
extension to the IMvcBuilder
returned by the AddMvc()
extension. MvcJsonOptions
exposes a SerializerSettings
property which you can configure in your action code.
So instead of configuring once before registering MVC, it's done as part of the MVC registration.
Example incorporating your setup:
services.AddMvc()
.AddJsonOptions( options =>
{
options.SerializerSettings.Formatting = Formatting.Indented;
options.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With