【问题标题】:MVC6 JsonConvert setting JsonResult of an action GloballyMVC6 JsonConvert 全局设置动作的 JsonResult
【发布时间】:2016-07-11 15:54:08
【问题描述】:

我在我的应用程序中有特定的 Json 格式要求,例如我想要特定的日期格式并且我想要忽略空值,所以我将我的代码放在 Startup.cs 方法配置中

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 设置,以便我的所有操作方法都使用它。

【问题讨论】:

标签: json.net asp.net-core-mvc


【解决方案1】:

在Startup.cs文件的ConfigureServices中查找services.AddMvc()语句,然后添加如下代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 1970-01-01
    相关资源
    最近更新 更多