【问题标题】:ShouldSerialize* methods are not called in Web API documentation using SWAGGER使用 SWAGGER 在 Web API 文档中未调用 ShouldSerialize* 方法
【发布时间】:2018-03-05 01:32:12
【问题描述】:

我将 Swagger 用于 Web API 文档。 在我的 Web API 中,我有以下实体:

public class BaseEntity
{
    public string BaseEntProp1{get;set;}
    public string BaseEntProp2{get;set;}

    public virtual bool ShouldSerializeBaseEntProp1()
    {
         return true;
    }

    public virtual bool ShouldSerializeBaseEntProp1()
    {
         return true;
    }
}

public class DerivedEntity1 : BaseEntity
{
    [JsonIgnore]
    public string DerEntProp1{get;set;}

    public string DerEntProp2{get;set;}

    public override bool ShouldSerializeBaseEntProp1()
    {
         return false;
    }

    public override bool ShouldSerializeBaseEntProp1()
    {
         return false;
    }
}

我使用 DerivedEntity1 作为 Web API 方法的输入参数并生成了 swagger 文档。

直到这一切都很好,但问题是,该文档中的 DerivedEntity1 JSON 字符串显示了应该排除的 BaseEntProp1 和 BaseEntProp2。有人可以帮我排除这些吗?

注意: 1. DerivedEntity1 的 DerEntProp1 属性被正确排除。 2. 确认一下,在生成文档后的启动方法中,我硬编码了以下内容:

    var temp = new DerivedEntity1 { 
                   BaseEntProp1 = "should be ignored", 
                   BaseEntProp2 = "this also should be ignored"};

    string tempJson = JsonConvert.SerializeObject(temp); 

以上测试通过,即 tempJson 没有 BaseEntProp1 和 BaseEntProp2。因此,我怀疑 SWAGGER 以某种方式未能调用正确的 ShouldSerialize* 方法。非常感谢任何帮助。

谢谢

【问题讨论】:

    标签: asp.net-web-api json.net swagger


    【解决方案1】:

    最后我以不同的方式解决了这个问题,因为这个问题与 Swagger 无关。

    我创建了具有虚拟属性的基本抽象类。在派生类中,我重载了这些属性并用 JsonIgnore 属性装饰。这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 2016-12-25
      • 2017-03-08
      • 1970-01-01
      相关资源
      最近更新 更多