This is a very simple Web API project. I have a data model, generated DbContext, and a controller.
When I add the [JsonIgnore]
attribute to certain properties on my model classes and then later make a change to the data model, the model classes get regenerated and my [JsonIgnore]
attribute is deleted. I understand why this happens and that I shouldn't be adding attributes to an auto-generated class. My question is, where should I be annotating classes with attributes, like [JsonIgnore]
for use with ASP.NET Web API?
ASP.NET Web API 4, RTW
How can you prevent a property from being serialized? You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows. If possible, make an object that could contain security-sensitive data nonserializable.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
We still use [JsonIgnore] attribute, adding it to the property which we do not want to be serialized. Add an alternate private property setter to the class with the same type as the original property. Then set the value to the original property in the implementation.
You should use view models. Basically define classes that will contain only the properties that you need to expose and then return those view models from your Web API actions. This way you don't have to worry about polluting your domain models with [JsonIgnore]
attributes especially if you don't want those properties to be ignored only for certain actions. In order to simplify the mapping between your domain models and view models you may take a look at AutoMapper.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With