【发布时间】:2018-04-14 01:52:28
【问题描述】:
我已将 [XmlIgnore] 添加到忽略的属性。它不工作。
型号:
public class PointOfInterest // Child model
{
public string Name { get; set; }
public int CityId { get; set; } // Foreign key
[JsonIgnore] // Used to avoid circular reference
[XmlIgnore]
public City City { get; set; } // Parent
}
将 application/xml 设置为 Accept 标头:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc() // Add MVC middleware to DI
.AddMvcOptions(option => option
// Add application/xml as Accept Header
.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()))
错误:
System.Runtime.Serialization.SerializationException:“WebApiDemo.Models.PointOfInterest”类型的对象图包含循环,如果不跟踪引用,则无法序列化。考虑使用将 IsReference 属性设置为 true 的 DataContractAttribute。
【问题讨论】:
-
错误信息显示:
Consider using the DataContractAttribute with the IsReference property set to true。你试过吗? -
是的。我将
[DataContract(IsReference = true)]添加到PointOfInterest。虽然循环引用错误消失了,但返回的 XML 格式很奇怪。 -
我不认为 XmlDataContractSerializerOutputFormatter 正在使用 XmlIgnoreAttribute 和朋友。它们由 XmlSerializer 使用,这是另一回事。
标签: c# xml-serialization asp.net-core-webapi