1

In ASP.NET Core-6 Web API, I am implementing Swagger Documentation.

I have this code.

SwaggerDocOptions:

public class SwaggerDocOptions
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Organization { get; set; }
    public string Email { get; set; }
}

Program.cs

builder.Services.AddSwaggerGen();
builder.Services.AddOptions<SwaggerGenOptions>()
    .Configure<IApiVersionDescriptionProvider>((swagger, service) =>
    {
        foreach (ApiVersionDescription description in service.ApiVersionDescriptions)
        {
            swagger.SwaggerDoc(description.GroupName, new OpenApiInfo
            {
                Title = swaggerDocOptions.Title,
                Version = description.ApiVersion.ToString(),
                Description = swaggerDocOptions.Description,
                TermsOfService = new Uri("mysite.org/LICENSE.md"),
                Contact = new OpenApiContact
                {
                    Name = swaggerDocOptions.Organization,
                    Email = swaggerDocOptions.Email
                },
                License = new OpenApiLicense
                {
                    Name = "MIT",
                    Url = new Uri("mysite.org/MyApp")
                }
            });
        }

        var security = new Dictionary<string, IEnumerable<string>>
        {
            {"Bearer", new string[0]}
        };

        swagger.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Description = "JWT Authorization header using the Bearer scheme.",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer",
            BearerFormat = "JWT"
        });

        swagger.OperationFilter<AuthorizeCheckOperationFilter>();

        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        swagger.IncludeXmlComments(xmlPath);

    });
// Register and Configure API versioning
builder.Services.AddApiVersioning(options =>
{
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.ReportApiVersions = true;
});

// Register and configure API versioning explorer
builder.Services.AddVersionedApiExplorer(options =>
{
    options.GroupNameFormat = "'v'VVV";
    options.SubstituteApiVersionInUrl = true;

});


// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();

I want the fields that are required to be specified in the Swagger Documentation. That is,

https://localhost:44361/swagger.index.html

However, when I lauched the Application, the required fields are not specified in

https://localhost:44361/swagger.index.html.

How do I achieve this?

Thanks

Ayobamilaye
  • 1,099
  • 1
  • 17
  • 46
  • You can simply add `[Required]` attribute to make it mandatory. – Anuraj Jul 21 '22 at 11:35
  • Does this answer your question? [How to specify if a field is optional or required in OpenAPI/Swagger?](https://stackoverflow.com/questions/40113049/how-to-specify-if-a-field-is-optional-or-required-in-openapi-swagger) – Vahid Jul 21 '22 at 12:34
  • @Anuraj - I already have [Required], but it's not solving the problem. – Ayobamilaye Jul 21 '22 at 12:54
  • for what fields you need to specify the required, can you add that code. – CodingMytra Jul 22 '22 at 05:51

1 Answers1

0

Add the [Required] attribute to the property of the class:

public class SwaggerDocOptions
{
    [Required]
    public string Title { get; set; }

    public string Description { get; set; }

    [Required]
    public string Organization { get; set; }

    public string Email { get; set; }
}

And don't forget add the [Produces("application/json")] attribute to the API controller. Its purpose is to declare that the controller's actions support a response content type of application/json:

[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class TodoController : ControllerBase
{
Xiaotian Yang
  • 499
  • 1
  • 2
  • 7
  • I am not using System.ComponentModel.DataAnnotations, but FluentApi. I even added [Required] in the model. Already I added [Produces("application/json")], but it's not showing required. – Ayobamilaye Sep 06 '22 at 09:29