.Net 6 + WebApi Basics 4 - Swagger UI
2023-01-02 20:58:27  .Net  >> .Net6  >> WebApi

Swagger

Swagger is a web service for generating, describing and invoking RESTful interfaces.

Simply, Swagger is a service that displays all interfaces you want to explicitly display in the project on the web page, and can perform interface calls and tests. Therefore, 3 main functions can Swagger achieve.

  1. Interface documentation

    List all interfaces in the project on the web page, so that back-end developers do not need to write special interface documents for front-end users;

  2. Updated interface information

    After the interface is updated, you only need to modify the Swagger description in the code to generate a new interface document in real time, thus avoiding the problem that the interface document is outdated and cannot be used

  3. Call the interface

    Through the Swagger page, we can directly call the interface, which reduces the debugging cost in the project development stage.

Common Ways to use Swagger

Next are some common ways to better use Swagger

  1. Comment
  2. Version Control
  3. JWT authentication

Comment in Swagger

We hope to add an introduction after each methods or interfaces to facilitate our testing and front-end reading, so that we make comments in Swagger for better understanding.

Step I. Turn on Documentation File Generation

There are two methods to turn on Documentation File Generation

Method A: From Project File (.csproj)

Right-click your project > Edit Project File > Modify GeneraterDocumentationFile tag to True.

1
2
3
4
<PropertyGroup>
//Add following code
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>

Project File

Method B: From Properties

Right-click the project -> Properties -> Build -> Output -> Documentation File -> Check to Generate a file containing API documentation

Properties

Step II. Add Comment to Swagger

Add comment as common way for C# to any Controller or Class with /// , then the comment will be shown on Swagger UI.

Add comments to controller
comments to controller

Add comments to Class
comments to Class

Result:
result

Note:

  1. If the return type is object, Schemas does NOT show the comment in Swagger UI.
    1
    2
    [HttpGet(Name = "GetWeatherForecast")]
    public IEnumerable<object> Get()
  2. However, If the get type is specified, Schemas DOES show the comment even the return type is object.
    1
    2
    [HttpPost(Name = "GetWeatherForecast")]
    public IEnumerable<object> Get(WeatherForecast weather_res)

Version Control in Swagger

First, we create a enum class to store the name of versions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// <summary>
/// Api Version Enums
/// </summary>
public enum ABC_Versions
{
/// <summary>
/// VersionV1
/// </summary>
V1=1.0,
/// <summary>
/// version V2
/// </summary>
V2=2.0
}

Second, go to Program.cs and modify AddSwaggerGen().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
builder.Services.AddSwaggerGen(options => {
//Single Version
// options.SwaggerDoc("V1", new OpenApiInfo
// {
// Title = $"Project Name",
// Version = "V1",
// Description = $"Project Name: Current version is {version}"
// });


//Multiple Versions
typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
{
//Add version introduction in Swagger
options.SwaggerDoc(version, new OpenApiInfo
{
Title = $"Project Name",
Version = version,
Description = $"Project Name: Current version is {version}"
});
});
});

typeof(ApiVersions).GetEnumNames().ToList().ForEach is to get all of the enum name from above Api Version Enums.

And, modify UseSwaggerUI().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(options => {
//Single Version
// options.SwaggerEndpoint($"/swagger/{version}/swagger.json",$"VERSION:{version}");

//Multiple Version
typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
{
//Switch version
//1st parameter is which json to choose.
//2nd parameter is just a name.
options.SwaggerEndpoint($"/swagger/{version}/swagger.json",$"VERSION:{version}");
});
});
}

Use SwaggerEndpoint to choose swagger’s json file to switch versions.

Finally, add an [ApiExplorerSettings(GroupName ="V1")] attribute to the function in controller.

1
2
3
4
5
6
7
8
9
10
11
12
[ApiExplorerSettings(GroupName ="V1")]
[HttpGet]
public IEnumerable<WeatherForecast> Get(Wea weather)
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}

Result

V1

V2

Since the attribute is set to V1 for Get(), the interface is only shown is the selected version is V1.
If GroupName doesn’t specified the version, the interface will be shown in all versions.

ApiExplorerSettings has two parameters.

[ApiExplorerSettings(GroupName ="V1", IgnoreApi = false)]

GroupName: Name of version

IgnoreApi: Whether the version is ignored.

When IgnoreApi is set to false,

IgnoreApiFalse


JWT Authentication

Simply go to Program.cs and modify AddSwaggerGen().
More details will be covered later post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
builder.Services.AddSwaggerGen(options => 
{
options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Description = "ADD Token into request head:Bearer Token",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
BearerFormat = "JWT",
Scheme = "Bearer"
});
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference {
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] { }
}
});
});

Next: .Net 6 + WebApi Basics 5

Last: .Net 6 + WebApi Basics 3


Good Day
😎