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

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

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

问题

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

  1. public class Dependency
  2. {
  3. public string Name { get; set; }
  4. [JsonConverter(typeof(VersionRangeConverter))]
  5. [SwaggerExclude]
  6. public VersionRange VersionRange { get; set; }
  7. }

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

  1. public class SwaggerExcludeFilter : ISchemaFilter
  2. {
  3. public void Apply(OpenApiSchema schema, SchemaFilterContext context)
  4. {
  5. if (schema?.Properties == null)
  6. {
  7. return;
  8. }
  9. var properties = context?.Type?.GetProperties().Where(x => x.GetCustomAttribute<SwaggerExcludeAttribute>() != null);
  10. foreach (PropertyInfo prop in properties ?? Enumerable.Empty<PropertyInfo>())
  11. {
  12. if (schema.Properties.ContainsKey(prop.Name))
  13. {
  14. schema.Properties.Remove(prop.Name);
  15. }
  16. }
  17. }
  18. }

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

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

英文:

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

  1. public class Dependency
  2. {
  3. public string Name { get; set; }
  4. [JsonConverter(typeof(VersionRangeConverter))]
  5. [SwaggerExclude]
  6. public VersionRange VersionRange { get; set; }
  7. }

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

  1. public class SwaggerExcludeFilter : ISchemaFilter
  2. {
  3. public void Apply(OpenApiSchema schema, SchemaFilterContext context)
  4. {
  5. if (schema?.Properties == null)
  6. {
  7. return;
  8. }
  9. var properties = context?.Type?.GetProperties().Where(x =&gt; x.GetCustomAttribute&lt;SwaggerExcludeAttribute&gt;() != null);
  10. foreach (PropertyInfo prop in properties ?? Enumerable.Empty&lt;PropertyInfo&gt;())
  11. {
  12. if (schema.Properties.ContainsKey(prop.Name))
  13. {
  14. schema.Properties.Remove(prop.Name);
  15. }
  16. }
  17. }
  18. }

> 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:

确定