Where should I add [JsonIgnore] to prevent serialization of certain properties?

This is a very simple web API project. I have a data model created by DbContext and a controller.

When I add the [JsonIgnore] attribute to certain properties in my model classes, and then make changes to the data model, the model classes are restored, and the [JsonIgnore] attribute is deleted. I understand why this is happening and that I should not add attributes to the automatically generated class. My question is: where should I annotate classes with attributes like [JsonIgnore] for use with ASP.NET Web API?

ASP.NET Web API 4, RTW

+4
source share
2 answers

You must use view models. Basically define classes that will contain only those properties that you need to present, and then return these view models from the web API actions. This way, you don’t have to worry about polluting your domain models with [JsonIgnore] attributes, especially if you do not want these properties to be ignored only for certain actions. To simplify the mapping between your domain models and view models, you can take a look at AutoMapper .

+5
source

Since you expressly declare that you are creating a very simple web API project, you can leave with a simple global replacement. Although I converted the project to use ASP.NET web APIs, I ran into the same problem. Since I regularly changed the database schema, it was just easier to return the original types, rather than dynamic or strongly typed view models, because the properties of the data that was wrapped were constantly changing.

Properties that must be ignored for serialization are all navigation properties created by EF. It also happens that all these properties are virtual. I made a replacement in the files (only for my data library project), replacing all public virtual with [Newtonsoft.Json.JsonIgnore] public virtual .

A quick and easy fix that allows you to test while the project is still in development. I agree that, in the end, you should probably migrate EF models to view models, but this simple way allows you to continue to work without them a little more.

+2
source

All Articles