在ASP.NET Core Web App中,AddJsonOptions和AddJsonFormatters之间的区别是什么?

时间:2017-11-25 23:44:36

标签: c# asp.net json asp.net-core-2.0

我正在尝试全面控制所有 json输出设置,就像正常的HTTP 200 OK结果一样,如模型验证失败(HTTP 400 BAD请求)等等。

我在startup.cs中遇到了这两种方法: -

  • AddJsonOptions(options => ...)
  • AddJsonFormatters(options => ...)

有人可以解释这两者之间的区别吗?为什么我会用一个而不是另一个?

FWIW,我也试图使用Newtonsoft JSON作为我的json提供商,设置如下:

var settings = new JsonSerializerSettings
{
    ContractResolver = new CamelCasePropertyNamesContractResolver(),
    Formatting = Formatting.None,
    NullValueHandling = NullValueHandling.Ignore,
    DateFormatHandling = DateFormatHandling.IsoDateFormat
};

喝彩!

1 个答案:

答案 0 :(得分:11)

AddJsonOptions

这提供了通过在服务集合上调用.AddMvc()来配置已经设置的serailization设置和合同解析程序的方法。您可以从AddJsonFormatters()看到AddMvc()已调用AddJsonOptions()。因此,JSON.net将用于序列化,并提供source code。但是,您可以在这种情况下使用services.AddMvc() .AddJsonOptions(o => { o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); 覆盖默认值并指定所需的合约解析程序和序列化程序设置,例如。

AddMvcCore()

AddJsonFormatters

如果您在服务集合上使用准系统AddJsonFormatters(),则默认情况下不会设置JSON序列化中间件的格式(DefaultContractResolver and default settings)。因此,您需要调用services.AddMvcCore() .AddJsonFormatters(o => { o.ContractResolver = new CamelCasePropertyNamesContractResolver(); o.NullValueHandling = NullValueHandling.Ignore; }); 才能明确设置和配置解析程序和序列化程序设置:

AddMvcCore()

摘要

您可以看到这两种方法非常相似。它们都存在的唯一原因是因为AddMvcCore()允许您设置或创建自己的序列化中间件。如果您喜欢AddMvc()提供但需要使用services.AddMvcCore().AddJsonFormatters()提供的JSON序列化格式的准系统设置,则只需致电AddMvc()

有关AddMvcCore() I TRIED THIS: int : vlen; set of int : LEN = 1..vlen; set of int : VECS = 1..2; array[VECS,LEN] of -25..25 : vector; var -600..700 : sumTotal; constraint exists(i,j,k,l in LEN where i!=k \/ j!=l)( exists(v,v2 in VECS)(sumTotal=(vector[v,i] * vector[v2,j] * abs(i-j)+vector[v,k] * vector[v2,l] * abs(k-l) ))); solve minimize sumTotal; output ["vector1=["]++[" \(vector[1,j])"|j in LEN]++[" ];\nvector2=["]++[" \(vector[2,j])"|j in LEN]++[" ];\nsumTotal=\(sumTotal);"] for vlen = 2; vector = [|-2,3|-4,5|]; 之间差异的更深入说明,请参阅see the source on GitHub repo

上的精彩帖子