Asp.net web api 在ASP.NET Web API上禁止具有空值的属性

Asp.net web api 在ASP.NET Web API上禁止具有空值的属性,asp.net-web-api,Asp.net Web Api,我创建了一个ASP.NETWebAPI项目,移动应用程序将使用该项目。我需要json响应来省略null属性,而不是将它们作为property:null返回 我如何才能做到这一点?在WebApiConfig中: config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};

我创建了一个ASP.NETWebAPI项目,移动应用程序将使用该项目。我需要json响应来省略null属性,而不是将它们作为
property:null
返回


我如何才能做到这一点?

WebApiConfig
中:

config.Formatters.JsonFormatter.SerializerSettings = 
                 new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
或者,如果需要更多控制,可以替换整个格式化程序:

var jsonformatter = new JsonMediaTypeFormatter
{
    SerializerSettings =
    {
        NullValueHandling = NullValueHandling.Ignore
    }
};

config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, jsonformatter);

如果您使用的是vnext,请在vnext web api项目中,将此代码添加到startup.cs文件中

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().Configure<MvcOptions>(options =>
        {
            int position = options.OutputFormatters.FindIndex(f =>  f.Instance is JsonOutputFormatter);

            var settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore
            };

            var formatter = new JsonOutputFormatter();
            formatter.SerializerSettings = settings;

            options.OutputFormatters.Insert(position, formatter);
        });

    }
public void配置服务(IServiceCollection服务)
{
services.AddMvc().Configure(选项=>
{
int position=options.OutputFormatters.FindIndex(f=>f.Instance为JsonOutputFormatter);
var settings=new JsonSerializerSettings()
{
NullValueHandling=NullValueHandling.Ignore
};
var formatter=新的JsonOutputFormatter();
formatter.SerializerSettings=设置;
options.OutputFormatters.Insert(位置,格式化程序);
});
}

我使用ASP.NET5 1.0.0-beta7在startup.cs文件中完成了这段代码

services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});

您还可以使用
[DataContract]
[DataMember(EmitDefaultValue=false)]
属性

对于ASP.NET Core 3.0,
Startup.cs
代码中的
ConfigureServices()
方法应包含:

services.AddControllers()
.AddJsonOptions(选项=>
{
options.JsonSerializerOptions.IgnoreNullValues=true;
});

config.Formatters.XmlFormatter没有相同的属性…:/由于Json.NET 5(以前的版本不确定),您也可以这样做:
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling=NullValueHandling.Ignore
-这将更新空值处理,而不重置任何其他Json序列化设置(如在属性的第一个字母上使用小写)是否可以让它仅为单个属性执行此操作?NullValueHandling=NullValueHandling.Ignore对我的结果不起作用如果更改是基于每个属性进行的,并且使用的是足够新的Json.Net版本,则可以在属性上使用此属性:
[JsonProperty](NullValueHandling=NullValueHandling.Ignore)]
。问题是什么?这是唯一一个涵盖xml和json响应的答案。