【问题标题】:Change System.Text.Json Serialization Options of a single ASP.NET Core API controller or single Action in ASP.NET Core 3在 ASP.NET Core 3 中更改单个 ASP.NET Core API 控制器或单个操作的 System.Text.Json 序列化选项
【发布时间】:2020-02-03 03:51:06
【问题描述】:

我有两个控制器控制器:ControllerA 和 ControllerB。每个控制器的基类是ControllerBase。

ControllerA需要在默认选项中反序列化JSON

JsonSerializerOptions.IgnoreNullValues = false;

ControllerB 需要使用选项反序列化 JSON

JsonSerializerOptions.IgnoreNullValues = true;

我知道如何在 Startup.cs 中将此选项设置为全局

services.AddControllers().AddJsonOptions( options => options.JsonSerializerOptions.IgnoreNullValues = true);

但是如何为 Controller 或 Action 设置特定的反序列化选项呢? (ASP.NET Core 3 API)

【问题讨论】:

标签: c# asp.net-core deserialization system.text.json


【解决方案1】:

正如韩飞所建议的,直接的答案是在ControllerB上使用属性NullValuesJsonOutput

public class NullValuesJsonOutputAttribute : ActionFilterAttribute
{
    private static readonly SystemTextJsonOutputFormatter Formatter = new SystemTextJsonOutputFormatter(new JsonSerializerOptions
    {
        IgnoreNullValues = true
    });

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        if (context.Result is ObjectResult objectResult)
            objectResult.Formatters.Add(Formatter);
    }
}

【讨论】:

  • 您可能希望将这个答案发布在我作为重复链接的问题上,因为这个问题可能会被关闭。
猜你喜欢
  • 1970-01-01
  • 2018-12-16
  • 2020-02-14
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2014-06-09
  • 2017-09-17
相关资源
最近更新 更多