1

I have a class with

[DataContract]
public class Request
{
   [DataMember]
   public int Id{get; set;}

   //calculated field 
   public int Salary{get; set;}

   [DataMember]
   public int Name{get; set;}

}

I was able to hide field "Salary" by not having the [DataMember] attribute. Is there a way I could hide/not expose that field in the request?

[DataContract]
public class EmployeeDetailResponse
{
   [DataMember]
   public int Id{get; set;}

   [DataMember]
   public string Grade{get; set;}

   //Used while calculating grade and should be hidden
   public int Salary{get; set;}

   [DataMember]
   public int Name{get; set;}

}

expected output : I will would like to use the Request as:

Request:

Id
Name

and Response as

Id
Grade
Name

Actual output is: Request:

Id
Salary (Not hidden)
Name

and Response as

Id
Grade
Salary (Not hidden)
Name

I'm testing this using swagger and expect to see only Id and Name in the request and when I enter the input values and execute, I would like to see Id, Grade and Name in the Response. Swagger is displaying Salary with its value. This is happening after upgrading to .net core 3.1. I expect Salary field not to be serialised and should not be exposed in the response

Dev
  • 1,451
  • 20
  • 30
  • @HenkHolterman I have updated the question - It is not hiding Salary and I'm able to see them in the response – Dev Apr 28 '20 at 15:12
  • @HenkHolterman I'm testing this using swagger and expect to see only Id and Name in the request and when I enter those values and execute, I would like to see Id, Grade and Name in the Response. It is displaying Salary with its value as well. This is happening after upgrading to .net core 3.1. I expect Salary field not to be serialised and should not be exposed in the response – Dev Apr 28 '20 at 15:52

1 Answers1

1

Use [JsonIgnore] from System.Text.Json.Serialization to hide fields from serialization/Swagger.

As best as I can tell, DataContract/DataMember is ignored completely.

Jonathan Allen
  • 68,373
  • 70
  • 259
  • 447