本文介绍了我应该在哪里被序列化添加[JsonIgnore]至prevent某些属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常简单的Web API项目。我有一个数据模型,所产生的DbContext,和一个控制器。

This is a very simple Web API project. I have a data model, generated DbContext, and a controller.

当我加入我的模型类的 [JsonIgnore] 属性某些属性,再后来更改了数据模型,模型类获得再生,我的 [JsonIgnore] 属性被删除。我理解为什么会这样,我应该不会被添加属性自动生成的类。我的问题是,我应该在哪里进行注释类与属性,如 [JsonIgnore] 与ASP.NET的Web API使用?

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

ASP.NET Web API 4, RTW

推荐答案

您应该使用视图模型。基本上定义将只包含您需要公开,然后从你的Web API操作返回的视图模型的属性的类。这样,您就不必担心与污染你的域模型[JsonIgnore] 属性特别是如果你不希望这些属性只对某些行为可以忽略不。为了简化您的域模型和视图模型之间的映射你可能看看。

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.

这篇关于我应该在哪里被序列化添加[JsonIgnore]至prevent某些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 14:42