How can we hide a property in WebAPI?

后端 未结 5 2068
春和景丽
春和景丽 2020-12-14 10:04

I have a model say under

public class Device
{        
        public int DeviceId { get; set; }
        public string DeviceTokenIds { get; set; }
        p         


        
相关标签:
5条回答
  • 2020-12-14 10:27

    I just figured out

    [IgnoreDataMember]
     public int DeviceId { get; set; }
    

    The namespace is System.Runtime.Serialization

    More information IgnoreDataMemberAttribute Class

    Learnt something new today.

    Thanks All.

    0 讨论(0)
  • 2020-12-14 10:30

    If you want to hide the data member of Resonse class with null parameter. Go to your project WebApiConfig file residing in App_start folder, add the following code:

    var jsonConfig = config.Formatters.JsonFormatter;
    jsonConfig.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
    
    0 讨论(0)
  • 2020-12-14 10:32

    There's good practice to use View Models for all GET/POST requests. In you case you should create class for receiving data in POST:

    public class InsertDeviceViewModel
    {        
        public string DeviceTokenIds { get; set; }
        public byte[] Data { get; set; }
        public string FilePwd { get; set; }        
    }
    

    and then map data from view model to you business model Device.

    0 讨论(0)
  • 2020-12-14 10:37

    If you are using Newtonsoft.Json

    you can hide the properties like this:

    public class Product
    {
        [JsonIgnore]
        public string internalID { get; set; };
        public string sku { get; set; };
        public string productName { get; set; };
    }
    

    and your serialized response will not include the internalID property.

    0 讨论(0)
  • 2020-12-14 10:50

    The use of the Attribute [NonSerialized] on top of the Property stops its from being Serialized in the outputting JSON/XML .

    public class Device
    {        
            [NonSerialized]
            public int DeviceId { get; set; }
    
            public string DeviceTokenIds { get; set; }
            public byte[] Data { get; set; }
            public string FilePwd { get; set; }        
    }
    
    0 讨论(0)
提交回复
热议问题