我在我的应用程序中有特定的Json格式要求,例如我想要特定的日期格式,我想要忽略空值,所以我把我的代码放在Startup.cs方法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
};
.....
}
以下是我的操作方法
的示例[HttpGet("[action]")]
public ActionResult GetSampleyData()
{
var model= new {StartDate=DateTime.Now, Name="test"};
return new JsonResult(model);
}
但结果不符合我的预期格式。如何在全局设置json设置,以便我的所有操作方法都使用它。
答案 0 :(得分:1)
在Startup.cs文件的ConfigureServices中查找services.AddMvc()语句,然后添加以下代码:
services.AddMvc()
.AddJsonOptions(o =>
{
o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
o.SerializerSettings.DateFormatString = "dd/MM/yyy hh:mm:ss";
}
);