gpt4 book ai didi

c# - AspNet Core - Controller 级别的输入/输出 JSON 序列化设置

转载 作者:太空狗 更新时间:2023-10-30 01:12:44 25 4
gpt4 key购买 nike

我的应用程序需要(几乎是默认的)JSON 序列化设置:

services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
});

仅对于一个 Controller ,我需要对两个输入使用不同的命名策略(我使用 [FromBody] myComplexObject 进行模型绑定(bind)并使用

进行输出
options.SerializerSettings.ContractResolver = new DefaultContractResolver();

我的问题几乎与 Web API: Configure JSON serializer settings on action or controller level 相同除了我要求 AspNet Core 2.2+,其中 IControllerConfiguration 不再存在。

Core 2.1+ 等效问题在此处有回复:Configure input/output formatters on controllers with ASP.NET Core 2.1

那里的答案似乎有些支离 splinter 或不完整 - 很难想象没有更简单的方法来实现这一目标。有人知道如何在单个 Controller 中对所有输入和输出使用 DefaultContractResolver 吗?

最佳答案

您链接的答案效果很好,但您可以通过将其包装在可应用于任何操作或 Controller 的属性中来进一步扩展它。例如:

public class JsonConfigFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result is ObjectResult objectResult)
{
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
};

var jsonFormatter = new JsonOutputFormatter(
serializerSettings,
ArrayPool<char>.Shared);

objectResult.Formatters.Add(jsonFormatter);
}

base.OnResultExecuting(context);
}
}

并将其添加到操作方法或 Controller 中:

[JsonConfigFilter]
public ActionResult<Foo> SomeAction()
{
return new Foo
{
Bar = "hello"
};
}

关于c# - AspNet Core - Controller 级别的输入/输出 JSON 序列化设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56127510/

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