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

前端 未结 2 1437
渐次进展
渐次进展 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.

    0 讨论(0)
  • 2021-01-13 00:44

    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.

    0 讨论(0)
提交回复
热议问题