How can we hide a property in WebAPI?

I have a model under

public class Device
{        
        public int DeviceId { get; set; }
        public string DeviceTokenIds { get; set; }
        public byte[] Data { get; set; }
        public string FilePwd { get; set; }        
}

      

Now I have an ASP.net Web API where there is a POST method under

[HttpPost]
[Route("AddDeviceRegistrations")]
public void InsertDeviceRegistrations(Device device)

      

If I expose WebAPI, obviously all fields will be available, eg.

{
  "DeviceId": 1,
  "DeviceTokenIds": "sample string 2",
  "Data": "QEBA",
  "FilePwd": "sample string 3"
}

      

I want that whenever I expose my WebAPI the DeviceID should not be exposed. I mean what I'm looking for

{

      "DeviceTokenIds": "sample string 2",
      "Data": "QEBA",
      "FilePwd": "sample string 3"
}

      

Is it possible? If so, how?

I can fix the problem by changing the function signature as

public void InsertDeviceRegistrations(string deviceTokenIds, byte[] data, string FilePwd).

      

But I wanted to know if this is possible or not? If so, how?

Thanks in advance.

+3


source to share


3 answers


I just realized

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

      

Namespace System.Runtime.Serialization



More Information IgnoreDataMemberAttribute Class

Learned something new today.

Thanks everyone.

+11


source


It is good practice to use viewmodels for all GET / POST requests. In this case, you must create a class to receive data in POST:

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

      



and then map the data from the view model to the business model Device

.

+2


source


Using the [NonSerialized] attribute on top of the property stops serializing when 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; }        
}

      

+1


source







All Articles