如何使用 swashbuckle 在 swagger 的发布请求描述中隐藏属性?

Iva*_*iji 13 c# swagger swashbuckle asp.net-core swashbuckle.aspnetcore

我是 ASP.NET Core 的新手,这个问题看起来很简单,但我在网上找不到合适的解决方案。所以问题就在这里。
这是我正在使用的类的结构。

public class Alert
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string AlertId { get; set; }
    public string Type { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

这是swagger中Post请求API的描述。

{
  "alertId": "string",
  "type": "string"
}
Run Code Online (Sandbox Code Playgroud)

由于我在发布请求中使用[DatabaseGenerated(DatabaseGeneratedOption.Identity)]注释是可选的。alertId我的目标是alertId仅隐藏帖子请求描述。
我正在使用 ASP.NET Core 3.1、EF Core(3.1.1) 和 Swashbuckle.AspDotNetCore(5.1.0)。
请帮忙。
谢谢。

Han*_*abi 21

您可以使用该Swashbuckle.AspNetCore.Annotations包,它允许您标记某些属性仅显示在输入参数中,某些属性仅显示在输出中。

在您的情况下,您想隐藏AlertId帖子的输入参数中的 ,您只需通过以下操作即可[SwaggerSchema]

public class Alert
{
    [SwaggerSchema(ReadOnly = true)]
    public string AlertId { get; set; }
    public string Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在文档中查看更多相关信息

ConfigureServices的方法中Startup.cs,在 Swagger 配置块中启用注释:

services.AddSwaggerGen(c =>
{
   ...

   c.EnableAnnotations();
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!每个人都建议使用 JsonIgnore,但这会阻止序列化,因此即使您的 GET 请求也会隐藏该字段。很高兴看到有一个实际的解决方案,而且是一个完全直接的解决方案。 (2认同)