【问题标题】:C# Swashbuckle: Obsolete model property shows without change in swaggerC# Swashbuckle:过时的模型属性显示没有大摇大摆的变化
【发布时间】:2018-07-09 08:07:06
【问题描述】:

我已在我的(输入)模型中将属性标记为过时

public class MyModel
{
   [Obsolete("Use 'OtherProperty'")]
   public string SomeProperty {get;set;}


   public List<string> OtherProperty {get;set;}
}

但是,swagger 没有显示这两个属性之间的区别,也没有显示消息。

有什么方法可以让我大摇大摆地尊重 Obsolete 属性?还是我需要自己把它放在属性上方的 xml-cmets 中?

【问题讨论】:

标签: c# asp.net-core .net-core swagger swashbuckle


【解决方案1】:

不幸的是,Swashbuckle 上还不支持过时的属性...

我们受到 OpenAPI 规范的限制,而 Swashbuckle 仍在使用 2.0
最接近的东西已弃用,但仅适用于不适用于属性的方法:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object

  • 一种选择是使用IDocumentFilter 破解某些东西以完全隐藏那些带有Obsolete 标记的属性,但这将是一条崎岖不平的道路。

  • 另一种选择是创建两个方法和两个模型,这样您就可以标记方法并转换到其中的方法,一切都会被弃用(我认为这有点混乱) /em> 但我已经在许多 web-api 中看到过这种模式

我认为您最好/最简单的解决方案是您建议添加一些 xml cmets 并指出不应使用该属性。

【讨论】:

  • OpenAPI 3.0 支持deprecated 用于模型和属性。但 Swashbuckle 似乎还不支持它。
  • 感谢@Helen 的澄清!你有任何关于 3.0 的使用/采用的统计数据吗?
  • 我没有统计数据,但这里有一个known OAS3 implementations 的列表。
  • 我对这个答案投了反对票,因为它误导了我,Swagger 根本不支持 Obsolete 属性。它受支持,并且 Swagger 行为是不在模型定义和示例中显示它。但是 IgnoreObsoleteProperties 标志必须在 Swagger Config 中设置,默认为 false。
【解决方案2】:

只需使用 [Obsolete] 属性(来自系统命名空间)装饰属性并将 Swagger 标志 IgnoreObsoleteProperties 设置为 true,它就对我有用。我还添加了属性 SomePropertySpecified,如果请求中存在 SomeProperty,它会由序列化程序自动设置为 true(空值并不意味着该属性不存在)。如果 SomePropertySpecified 为真,我有一个自定义逻辑来返回适当的错误消息。

public class Item
{
    [Obsolete]
    public string SomeProperty { get; set; }
    
    [JsonIgnore]
    public bool SomePropertySpecified { get; set; }

    public List<string> OtherProperty { get; set; }
}

类 SwaggerConfig:

public class SwaggerConfig
{
    public static void Register()
    {
        GlobalConfiguration.Configuration 
            .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1", "Demo");
                    c.IgnoreObsoleteProperties();
                })
            .EnableSwaggerUi(c =>
                {
                    c.DocExpansion(DocExpansion.Full);
                });
    }
}

招摇用户界面:

【讨论】:

    【解决方案3】:
    [Obsolete]
    public string Property {get; set;}
    
    services.AddSwaggerGen(x => 
        // your other settings...
        x.IgnoreObsoleteProperties();
    )
    

    这对我有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2015-12-14
      相关资源
      最近更新 更多