[英]ASP.NET WebAPI Creating one-level JSON
Domain程序集中有很多相關的實體。 例如People
具有到FamilyRelations
、 Houses
和Persons
導航屬性(Level1)。 除此之外, Houses
有自己的 nav.prop(Level2)到Address
和Address
(Level3)到City
、 Street
...等。 當我將LazyLoadingEnabled
設置為 true 時,我將獲得所有相關實體的 JSON(在屏幕左側)。
如何僅獲得一層嵌套(如在 scree 中的右側)或將其他級別設置為NULL
值(因為我設置了 Newtonsoft.Json.NullValueHandling.Ignore)?
我可以在不使用.Include
到每個實體的情況下實現它嗎?
我的班級:
public class People : BaseEntity
{
public int PersonID { get; set; }
public int HouseID { get; set; }
public int PeopleNumber { get; set; }
public int? FamilyRelationID { get; set; }
//FK to House
public virtual House Houses { get; set; }
//FK to Person
public virtual Person Persons { get; set; }
//FK to FamilyRelations
public virtual FamilyRelations FamilyRelations { get; set; }
}
WebAPI 配置:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling
= Newtonsoft.Json.NullValueHandling.Ignore;
我沒有任何解決方案,因為我沒有足夠的經驗。
所以,我需要你的建議,關於它的建議。 抱歉我的英語,如果我必須添加更多信息,請告訴我。 謝謝
更新
我嘗試在映射類中添加[JsonIgnore]
或忽略這些屬性,但是當我請求get/House
我需要從Address
獲取字段而沒有 nav.prop 並且當請求get/People
我不會 nedd Address
。 結果我不能忽視它。
切勿將跟蹤對象返回給控制器。 您的業務邏輯代碼(不應存在於控制器中)應該將您的數據庫感知對象映射到 POCO。 這可以像使用一樣簡單
var poco = AutoMapper.Map<People>(livePerson)
並且您在映射配置文件中設置以忽略這些屬性,因此它們不會被復制。
請注意,我的 automapper-fu 很生疏,因為語法是粗略的代碼。
對於任何盲映射,您都需要非常小心,因為它會使您暴露於Mass Assignment 漏洞。 這同樣適用於直接訪問您的實時跟蹤對象。 如果用戶在他們的數據中看到 IsAdmin: false,他們可能會變得狡猾並發布 IsAdmin: true。 這可以通過盲分配保存到您的數據庫中。
如果您正在尋找一種在json
序列化中忽略導航屬性的方法, 這個答案可以提供幫助,您可以通過它忽略json
序列化中的導航屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.