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

Is there way to choose between Newtonsoft.json and System.Text.Json in Actions?

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

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

据我所知,没有为特定控制器指定 Jsonconvert 的内置方法。

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

我建议你可以尝试使用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核心修改了iresoucefilter不支持change is formater.