简体   繁体   English

调用 Web API 时有条件地忽略属性

[英]Conditional ignore a property while calling Web API

I want to ignore one property while returning data from Web API call.我想在从 Web API 调用返回数据时忽略一个属性。 Here is my class.这是我的课。

public class Customer 
{
    public Customer(int id, string name)
    {
       ID = id;
       Name = name;
    }

    public Customer(int id, string name, int age)
    {
       ID = id;
       Name = name;
       Age = age;
    }

    int Id {get; set}
    string Name {get; set}
    int Age {get; set}
 }

and here are Apis in the Controller class这是Controller类中的Api

Customer GetCustomerById(int id)
{
    var customer = GetCustomerData();
    // I want to return only Id and Name, but it is returning age also with value 0
    return new Customer(customer.id, customer.Name);    
}


List<Customer> GetCustomerByName(string name)
{
    var customers = GetCustomerDataByName(name); 
    // Over here I need all three properties, hence I am not using JsonIgnore on Age Property
    return customers.Select(x => new Customer(x.id, x.name, x.age)).ToList();
}

You can change the age properly to be nullable int?您可以将年龄正确更改为可为空的int? . . And then configure the json converter to ignore null params:然后将 json 转换器配置为忽略空参数:

services.AddMvc()
.AddJsonOptions(options =>
{
    options.JsonSerializerOptions.IgnoreNullValues = true;
});

for more info look here .更多信息请看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM