[英]Change System.Text.Json Serialization Options of a single ASP.NET Core API controller or single Action in ASP.NET Core 3
I'm having two controller controllers: ControllerA and ControllerB.我有两个控制器控制器:ControllerA 和 ControllerB。 The base class of each controller is ControllerBase.
每个控制器的基类是 ControllerBase。
The ControllerA needs to deserialize JSON in the default option ControllerA 需要在默认选项中反序列化 JSON
JsonSerializerOptions.IgnoreNullValues = false;
The ControllerB needs to deserialize JSON with option ControllerB 需要使用选项反序列化 JSON
JsonSerializerOptions.IgnoreNullValues = true;
I know how to set this option global in Startup.cs我知道如何在 Startup.cs 中全局设置此选项
services.AddControllers().AddJsonOptions( options => options.JsonSerializerOptions.IgnoreNullValues = true);
But how to set specific deserialize options to Controller or Action?但是如何为 Controller 或 Action 设置特定的反序列化选项? (ASP.NET Core 3 API)
(ASP.NET Core 3 API)
As suggested by Fei Han, the straight-forward answer is to use on ControllerB the attribute NullValuesJsonOutput
:正如 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.