C# Swashbuckle:过时的模型 属性 显示 swagger 没有变化

C# Swashbuckle: Obsolete model property shows without change in swagger

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

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


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

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

有什么方法可以让我大摇大摆地遵守 Obsolete 属性?或者我需要把它放在 属性 上面的 xml-评论中吗?

遗憾的是,Swashbuckle 上尚不支持过时的属性...

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

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

  • 另一种选择是创建两个方法和两个模型,这样你就可以标记方法并将转换到其中的方法,一切都会被弃用(我认为这个有点乱) 但是我看到很多web-api

我认为您的 best/easiest 解决方案是您建议的添加一些 xml 注释,指出不应使用 属性。

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

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

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

Class SwaggerConfig:

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

招摇UI:

[Obsolete]
public string Property {get; set;}
services.AddSwaggerGen(x => 
    // your other settings...
    x.IgnoreObsoleteProperties();
)

这对我有用