0

I have specific Json formatting requirements in my application for example I want specific date formatting and I want null values to be ignored so I put my code in Startup.cs method configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IHttpContextAccessor contextAccessor)
    {

.....
  JsonConvert.DefaultSettings = () => new JsonSerializerSettings
   {
    DateFormatString = "dd/MM/yyy hh:mm:ss" ,                 
     NullValueHandling = NullValueHandling.Ignore

   };
.....

}

Here is an example of my action method

[HttpGet("[action]")]
 public ActionResult GetSampleyData()
  {
    var model= new {StartDate=DateTime.Now, Name="test"};             
     return new JsonResult(model);
  }

But the result is not being in the format I expected. How can I set the json settings Globally sothat all my action methods use it.

Helen Araya
  • 1,886
  • 3
  • 28
  • 54
  • 1
    asp.net-mvc6 has its own internal `JsonSerializerSettings`. I think you should be able to access and modify them as shown in [asp.net core 1.0 web api use camelcase](https://stackoverflow.com/questions/38139607/asp-net-core-1-0-web-api-use-camelcase) – dbc Jul 12 '16 at 04:23

1 Answers1

1

Look for the services.AddMvc() statement in ConfigureServices in the Startup.cs file, and then add the following code:

        services.AddMvc()
            .AddJsonOptions(o =>
            {
                o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                o.SerializerSettings.DateFormatString = "dd/MM/yyy hh:mm:ss";
            }
        );
Chris
  • 523
  • 1
  • 5
  • 16