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.
This is all you need to add to hide the field in the Swagger ui: @ApiModelProperty(hidden = true) private List<Reservation> reservations; That would hide the reservation list from showing.
If you mark field/property as internal or protected or private , it will be ignored automatically by swashbuckle in swagger documentation. Update: Obviously, those properties/fields won't be populated in request/response.
Another simple approach is to use the ApiExplorerSettings attribute on all the methods for which documentation needs not to be created. You can apply ApiExplorerSettings on the Controller also to be able to ignore all methods under that Controller.
To hide the "Models" section, add defaultModelsExpandDepth: -1 to the Swagger UI configuration code in your index. html . Note the option name uses plural Model*s* not Model . Swagger UI also has many other configuration options that control API documentation rendering.
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();
});
You can add the [JsonIgnore]
attribute to the AlertId field to ensure that the post request will not get the content of the AlertId.
public class Alert
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[JsonIgnore]
public string AlertId { get; set; }
public string Type { get; set; }
}
Here it the test result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With