Control [JsonIgnore] in ASP.NET Web API at runtime

As you know, ASP.NET web api (ApiController) automatically gives a JSON response through NewtonSoft.JSON.

My three-level model 1: MANY: 1 EF is requested in several ways, and it works fine by applying the [JsonIgnore] attribute to some virtual properties to avoid a callback problem. (I use the third solution in this (link) )

but my problem is that sometimes I need to use json-ignored properties to query with the model.

Is there a way to control the [JsonIgnore] attribute at runtime? Or is there any method to turn a property on and off that should be ignored in NewtonSoft.JSON at run time?

+4
source share
1 answer

I know two ways to solve this problem:

  • You can add an additional logical property (with a specific name) to your model. This solution is very simple, but requires changes to your model.
  • You can write your own IContractResolver . This method is more complex, but more flexible.

Both of the solutions described here are: "Serializing a Conditional Property" http://james.newtonking.com/json/help/index.html?topic=html/ConditionalProperties.htm

+2
source

Source: https://habr.com/ru/post/1443818/


All Articles