我使用ASP.NET Core 5,不想从Newtonsoft.Json
迁移到System.Text.Json
,但在某些情况下,我想在控制器操作中使用System.Text.Json
以提高性能。
例如,在ActionA中,我想使用Newtonsoft.Json
序列化器的默认行为,在ActionB中,我想将行为更改为System.Text.Json
序列化器。
我使用ASP.NET Core 5,不想从Newtonsoft.Json
迁移到System.Text.Json
,但在某些情况下,我想在控制器操作中使用System.Text.Json
以提高性能。
例如,在ActionA中,我想使用Newtonsoft.Json
序列化器的默认行为,在ActionB中,我想将行为更改为System.Text.Json
序列化器。
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