在Actions中有没有办法在Newtonsoft.json和System.Text.json之间进行选择



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

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

据我所知,没有构建特定控制器的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();
}

如果你想为模型绑定器设置转换,唯一的方法是创建一个cusotmer modle绑定器,并根据每个模型类型修改json格式化程序。根据asp.net核心已经修改了iresoucefilter以不支持更改is格式化程序,这是无法实现的。

最新更新