gpt4 book ai didi

c# - 有没有办法在 Actions 中选择 Newtonsoft.json 和 System.Text.Json?

转载 作者:行者123 更新时间:2023-12-05 06:02:30 33 4
gpt4 key购买 nike

我使用 ASP.NET Core 5,我不想从 Newtonsoft.Json 迁移到 System.Text.Json,但在某些情况下,我想要使用 System.Text.Json 来提高 Controller 操作的性能。

例如,在 ActionA 中,我想使用 Newtonsoft.Json 序列化程序的默认行为,在 ActionB 中,我想将行为更改为 System.Text.Json 序列化程序.

最佳答案

据我所知,没有内置方法可以为特定 Controller 指定 Jsonconvert。

如果你想修改生成的json结果jsonconvert,我建议你可以尝试使用这种方式。

我建议您可以尝试使用 actionfilter 来实现您的要求。

通过使用 actionfilter,您可以修改输入格式化程序以使用其他 jsonconvert 来转换数据。

public class CaseActionAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext ctx)
{
if (ctx.Result is ObjectResult objectResult)
{
objectResult.Formatters.Add(new SystemTextJsonOutputFormatter(new JsonSerializerOptions
{
IgnoreNullValues = true
}));
}
}
}

用法:

    [HttpPost]
[CaseAction]
public ActionResult Index([FromForm]Member member) {
if (ModelState.IsValid)
{
RedirectToAction("Index");
}

return Ok();
}

如果要为模型绑定(bind)器设置转换,唯一的方法是创建一个客户模型绑定(bind)器并根据每个模型类型修改 json 格式化程序。根据 asp.net core 修改了 iresoucefilter 不支持 change is formater,没有办法实现。

关于c# - 有没有办法在 Actions 中选择 Newtonsoft.json 和 System.Text.Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66907652/

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