返回

.NET Core Razor page/MVC 返回json忽略空属性

2022-12-04 .NET Core Razor json 1762 0

.NET Core Razor page/MVC 返回json忽略空属性,修改program.cs。

添加配置

builder.Services.AddRazorPages()

.AddJsonOptions(options => {

    options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;

});

这个options里的DefaultIgnoreCondition枚举包含如下设置:

//
    // 摘要:
    //     Controls how the System.Text.Json.Serialization.JsonIgnoreAttribute ignores properties
    //     on serialization and deserialization.
    public enum JsonIgnoreCondition
    {
        //
        // 摘要:
        //     Property will always be serialized and deserialized, regardless of System.Text.Json.JsonSerializerOptions.IgnoreNullValues
        //     configuration.
        Never,
        //
        // 摘要:
        //     Property will always be ignored.
        Always,
        //
        // 摘要:
        //     Property will only be ignored if it is null.
        WhenWritingDefault,
        //
        // 摘要:
        //     If the value is null, the property is ignored during serialization. This is applied
        //     only to reference-type properties and fields.
        WhenWritingNull
    }

这样就可以在输入Json的时候忽略null值了。

您可能感兴趣:

阿里云 云服务器 99元1年 2核2G 3M固定带宽 续费与新购同价

DOVE 网络加速器 梯子 免费 试用

椤堕儴