gpt4 book ai didi

c# - 在 ASP.NET Core Web 应用程序中,AddJsonOptions 和 AddJsonFormatters 之间有什么区别?

转载 作者:太空狗 更新时间:2023-10-29 17:42:57 24 4
gpt4 key购买 nike

我正在尝试全面控制所有 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
};

最佳答案

添加Json选项

这提供了配置序列化设置和契约解析器的方法,它们已经通过在服务集合上调用 .AddMvc() 来设置。从source code可以看出AddJsonFormatters() 已被 AddMvc() 调用。因此,JSON.net 将用于序列化 DefaultContractResolver and default settings假如。但是,您可以在这种情况下使用 AddJsonOptions() 来覆盖默认值并指定所需的契约(Contract)解析器和序列化器设置,例如

services.AddMvc()
.AddJsonOptions(o =>
{
o.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
o.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});

AddJsonFormatters

如果您在服务集合上使用准系统 AddMvcCore(),则默认情况下不会设置 JSON 序列化中间件的格式 (see the source on GitHub repo)。因此,您将需要调用 AddJsonFormatters() 以显式设置和配置解析器和序列化器设置:

services.AddMvcCore()
.AddJsonFormatters(o =>
{
o.ContractResolver = new CamelCasePropertyNamesContractResolver();
o.NullValueHandling = NullValueHandling.Ignore;
});

总结

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

要更深入地了解 AddMvc()AddMvcCore() 之间的区别,请参阅 What is the difference between AddMvc() and AddMvcCore()? 上的精彩帖子

关于c# - 在 ASP.NET Core Web 应用程序中,AddJsonOptions 和 AddJsonFormatters 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47491618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com