skip to Main Content

I want to implement/configure Swagger in my project.

I have installed (Swashbuckle) package which is necessary for swagger implementation.

Where should I need to add the swagger configuration or which file should I have to include.

2

Answers


  1. If you will create an project from correct template it already comes with Swagger pre-setup. For example you can use the ASP.NET Core web API template (via your IDE or using dotnet new command with webapi template name). It includes (for .NET 7):

    • Preinstalled packages:

      <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.7"/>
      <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
      
    • Swagger set up (in Program.cs):

      // ...
      builder.Services.AddEndpointsApiExplorer();
      builder.Services.AddSwaggerGen();
      
      // ...
      
      if (app.Environment.IsDevelopment()) // by default enabled only for dev.
      {
           app.UseSwagger();
           app.UseSwaggerUI();
      }
      

    Read also:

    Login or Signup to reply.
  2. .NET 7 WebAPI project you need to configure it on Program.cs file.

    You need to add Swagger generator to the services collection.

    var builder = WebApplication.CreateBuilder(args);
    //Add the Swagger generator to the services collection
    builder.Services.AddSwaggerGen();
    

    Example to configure Swagger with JWT Authorization is as follows:

    builder.Services.AddSwaggerGen(option =>
    {
        option.SwaggerDoc("v1", new OpenApiInfo { Title = "Demo API", Version = "v1" });
        option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            In = ParameterLocation.Header,
            Description = "Please enter a valid token",
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
            BearerFormat = "JWT",
            Scheme = "Bearer"
        });
        option.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                new string[]{ }
            }
        });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search