Where should I add [JsonIgnore] to prevent certain properties from being serialized?

前端 未结 2 1438
渐次进展
渐次进展 2021-01-13 00:28

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 prop

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-13 00:38

    Because you say explicitly that you are creating a very simple Web API project, you might be able to get away with a simple global replace. While I was converting a project to use ASP.NET Web API, I ran into the same problem. Because I was changing the Database Schema regularly it was simply easier to return the original types rather than dynamic or strongly typed view models since the properties of the data being wrapped was constantly changing.

    The properties that needed to be ignored for serialization happen to be all the Navigation Properties generated by EF. It also happens that all these properties are virtual. I did a replace in files (scoped to only my data library project) replacing all public virtual with [Newtonsoft.Json.JsonIgnore] public virtual.

    A quick and easy fix to allow testing while the project is still in development. I agree that in the end, you should probably wrap the EF models into view models, but this simple method can allow you to keep working without them for a bit longer.

提交回复
热议问题