如何在SwaggerResponse模型中隐藏/排除属性?不是请求,而是响应。

huangapple go评论97阅读模式
英文:

How to hide/exclude property from SwaggerResponse Model? Not Request but Response

问题

以下是需要从Swagger响应模型中排除VersionRange属性的类:

public class Dependency
{       
    public string Name { get; set; }        

    [JsonConverter(typeof(VersionRangeConverter))]
    [SwaggerExclude]       
    public VersionRange VersionRange { get; set; }
}

我尝试使用带有ISchemaFilter的属性来排除SwaggerResponse模型中的属性,但没有成功。

public class SwaggerExcludeFilter : ISchemaFilter
{
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties == null)
        {
            return;
        }

        var properties = context?.Type?.GetProperties().Where(x => x.GetCustomAttribute<SwaggerExcludeAttribute>() != null);

        foreach (PropertyInfo prop in properties ?? Enumerable.Empty<PropertyInfo>())
        {
            if (schema.Properties.ContainsKey(prop.Name))
            {
                schema.Properties.Remove(prop.Name);
            }
        }
    }
}

我不想使用protected、internal访问修饰符,因为我希望在序列化和反序列化过程中考虑该属性。

[System.Text.Json.Serialization.JsonIgnore] 属性也没有效果。

英文:

Following is the Class from which VersionRange property needs to be excluded from SwaggerResponseModel :

public class Dependency
{       
    public string Name { get; set; }        

    [JsonConverter(typeof(VersionRangeConverter))]
    [SwaggerExclude]       
    public VersionRange VersionRange { get; set; }
}

I have tried using Attribute with ISchemaFilter to exclude property from SwaggerResponse model but it did not work out.

 public class SwaggerExcludeFilter : ISchemaFilter
    {
        public void Apply(OpenApiSchema schema, SchemaFilterContext context)
        {
            if (schema?.Properties == null)
            {
                return;
            }

            var properties = context?.Type?.GetProperties().Where(x =&gt; x.GetCustomAttribute&lt;SwaggerExcludeAttribute&gt;() != null);

            foreach (PropertyInfo prop in properties ?? Enumerable.Empty&lt;PropertyInfo&gt;())
            {
                if (schema.Properties.ContainsKey(prop.Name))
                {
                    schema.Properties.Remove(prop.Name);
                }
            }
        }
    }

> I do not want to use protected, internal access specifiers as I want
> property to consider during Serialization and De-Serialization.

<br>

> [System.Text.Json.Serialization.JsonIgnore] Attribute do not have
> effect either.

答案1

得分: 1

我相信,你会在这里这里找到答案。
Brhav为此实现了[SwaggerIgnore]属性。

英文:

I believe, you'll find the answer here and here.
Brhav implemented the [SwaggerIgnore] attribute for that.

huangapple
  • 本文由 发表于 2023年8月9日 06:46:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76863589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定