在 Actions 中,是否有选择 Newtonsoft.json 和 System.Text.Json 的方法?

4

我使用ASP.NET Core 5,不想从Newtonsoft.Json迁移到System.Text.Json,但在某些情况下,我想在控制器操作中使用System.Text.Json以提高性能。

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


不是一个好主意。出于性能原因,.NET Core已经进行了优化,不再使用newtonsoft。最好立即采用新的工作方式。 - Philip Stuyck
1个回答

1
据我所知,没有内置的方法可以为特定控制器指定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();
    }

如果您想为模型绑定设置转换器,唯一的方法是创建自定义模型绑定器,并根据每个模型类型修改JSON格式化程序。无法根据ASP.NET Core已修改的iresoucefilter实现更改其格式化程序。


我认为这里缺少处理返回JsonResult的情况。 - King King

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接