Search code examples
c#asp.net-coreswaggerswashbuckleswashbuckle.aspnetcore

How to hide a property just in post request description of swagger using swashbuckle?


I am new to ASP.NET Core and this question looks simple but I couldn't find a proper solution online. So here's the problem.
This is the structure of the class that I am using.

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

}

This is the description for the Post request API in swagger.

{
  "alertId": "string",
  "type": "string"
}

Since I am using [DatabaseGenerated(DatabaseGeneratedOption.Identity)] annotation alertId in the post request is optional. My aim is to hide alertId from the post request description only.
I am using ASP.NET Core 3.1, EF Core(3.1.1) and Swashbuckle.AspDotNetCore(5.1.0).
Please Help.
Thank you.


Solution

  • You can use the Swashbuckle.AspNetCore.Annotations package, it allows you to mark that some properties are only displayed in the input parameters, and some are only displayed in the output.

    In your case, you want to hide the AlertId in the input parameter of the post, you just need to do this by the [SwaggerSchema]:

    public class Alert
    {
        [SwaggerSchema(ReadOnly = true)]
        public string AlertId { get; set; }
        public string Type { get; set; }
    }
    

    See more about it in the Documentation

    In the ConfigureServices method of Startup.cs, enable annotations within in the Swagger config block:

    services.AddSwaggerGen(c =>
    {
       ...
    
       c.EnableAnnotations();
    });