ASP.NET MVC – Where to Add [JsonIgnore] to Prevent Serialization

asp.net-mvc

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

Best Answer

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.

Related Question