Helen Araya
Helen Araya

Reputation: 1946

MVC6 JsonConvert setting JsonResult of an action Globally

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.

Upvotes: 0

Views: 145

Answers (1)

Chris
Chris

Reputation: 572

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

Upvotes: 1

Related Questions