【问题标题】:Ignore property from XML serialization/deserialization in ASP.NET Core 2在 ASP.NET Core 2 中忽略 XML 序列化/反序列化的属性
【发布时间】: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


【解决方案1】:

根据错误消息尝试使用 DataContractAttributeIsReference 设置:

Consider using the DataContractAttribute with the IsReference property set to true.

【讨论】:

    猜你喜欢
    • 2013-08-17
    • 2014-05-21
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多