更改单个 ASP.NET Core API 控制器或 ASP.NET Core 3 中单个操作的 System.Text.Json 序列化选项

Mag*_*uro 8 c# deserialization asp.net-core system.text.json

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

ControllerA默认需要反序列化JSON

JsonSerializerOptions.IgnoreNullValues = false;
Run Code Online (Sandbox Code Playgroud)

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

JsonSerializerOptions.IgnoreNullValues = true;
Run Code Online (Sandbox Code Playgroud)

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

services.AddControllers().AddJsonOptions( options => options.JsonSerializerOptions.IgnoreNullValues = true);
Run Code Online (Sandbox Code Playgroud)

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

McX*_*McX 3

正如 Fei Han 所建议的,直接的答案是在 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);
    }
}
Run Code Online (Sandbox Code Playgroud)