7

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() }
            };

1 Answer 1

18

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());
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.