Adding Swagger to ASP.NET Core Web API Project

2 minute read

1. What is swagger?

Swagger is an open-source set of rules and specifications. It is used for API documentation and testing the API endpoints. Swagger UI generates documentation based on the Swagger specification and provides an interactive UI for testing APIs and experimenting with different parameters and options.

2. How to enable the swagger in .NET Core or .NET 7/8?

  1. Go to the startup.cs file or program.cs file
  2. Add the Swagger services under the ‘ConfigureServices’ method.
  3. Add the following middleware under the ‘Configure’ method i.e, Swagger and Swagger UI.
  4. Build and run the API.
  5. Go to http://localhost:8080/swagger to view your API documentation from Swagger.

3. Adding swagger in ASP.NET Core WEB API Project

```

public void ConfigureServices(IServiceCollection services)
{
  // Swagger
  services.AddEndpointsApiExplorer();

  services.AddSwaggerGen(c =>
  {
      //c.SwaggerDoc("v1", new Info { Title = "API title", Version = "v1" });
      c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
      {
          Description = @"JWT Authorization header using the Bearer scheme.
            Enter 'Bearer' [space] and then your token in the text input below.
            Example: 'Bearer xyztokenabc'",
          Name = "Authorization",
          In = ParameterLocation.Header,
          Type = SecuritySchemeType.ApiKey,
          Scheme = "Bearer"
      });

      c.AddSecurityRequirement(new OpenApiSecurityRequirement() {
      {
        new OpenApiSecurityScheme
        {
          Reference = new OpenApiReference
          {
            Type = ReferenceType.SecurityScheme,
            Id = "Bearer"
          },
          Scheme = "oauth2",
          Name = "Bearer",
          In = ParameterLocation.Header
        },
        new List<string>()
      }
  });

}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
    app.UseSwagger();
    app.UseSwaggerUI();
  }
  etc...
```

Leave a comment