0

I have a list of strings in my web.config that describes the names of the model members (generated by Entity Framework) that are allowed to be serialized in my web api.
How do I e.g. set the [IgnoreDataMember] attribute during runtime?
The idea is, that not all the data should be exposed and the configuration what should be exposed, should be configurable without recompilation.
So far, I am just setting all the values of the members not contained in that list to null. But this solution is not optimal because e.g. members of type datetime are serialized to "0001-01-01T00:00:00" and in addition, the response contains a lot of unnecessary information (the responses can grow up to 150MB). So it would be nicer to simply remove the members from the serialization process.

Chris
  • 234
  • 1
  • 11

2 Answers2

1

You can use the attributes:

[XmlIgnore] for XML or [JsonIgnore] for JSON.

For example:

[XmlIgnore]
public string MyString { get; set; }

or

[JsonIgnore]
public string MyString { get; set; }

Hope this helps.

Geoff James
  • 3,122
  • 1
  • 17
  • 36
  • Also, don't forget to use `System.Xml.Serialization` or `Newtonsoft.Json` respectively. – Geoff James May 04 '16 at 11:52
  • `[IgnoreDataMember]` works for both, I know that. But this has to be set on runtime depending on the configuration... – Chris May 04 '16 at 11:53
  • I see. You could write your own JSON converter that can use your conditionals at runtime. Another post that might help: [here](http://stackoverflow.com/questions/27397494/web-api-conditional-serialization-of-properties-at-runtime) – Geoff James May 04 '16 at 12:08
0

I worked around it with [DataMember(EmitDefaultValue = false)]. So all my properties which are set to null are not included in the response. However, this is not the best solution because now I can't send any null values and swagger also shows the full model.

Chris
  • 234
  • 1
  • 11