Integrate Swagger with ASP.NET Core Web API

Once you build the Web APIs required by your ASP.NET Core web application,
you typically want to test them by invoking their actions. The best way to do so
is by building a client application using HttpClient or Ajax. However, creating
such a client can be time consuming. You might want to quickly test the Web APIs
before moving ahead with your further development. That's where
Swagger can be helpful.
To see how Swagger can be integrated with ASP.NET Core Web API, begin by
creating a new API project using Visual Studio.

Once the project is created add the following NuGet packages to it:
- Swashbuckle.AspNetCore
- Swashbuckle.AspNetCore.Swagger
- Swashbuckle.AspNetCore.SwaggerUI
These NuGet packages are shown below after adding them successfully to the
project.

Then, add a new API Controller named ValuesController to the Controllers
folder.

Modify the ValuesController as shown below:
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public IEnumerable<string> Get()
{
return new string[]
{ "Hello World!",
"Hello Galaxy!",
"Hello Universe!"
};
}
[HttpGet("{id}")]
public string Get(int id)
{
return "Hello";
}
[HttpPost]
public string Post([FromBody]string value)
{
return "Hello World!";
}
[HttpPut("{id}")]
public string Put(int id, [FromBody]string value)
{
return "Hello Galaxy!";
}
[HttpDelete("{id}")]
public string Delete(int id)
{
return "Hello Universe!";
}
}
This is not a recommended REST style controller but works for our testing
purposes.
Then open Startup.cs file and modify the ConfigureServices() action as shown
below:
public void ConfigureServices(
IServiceCollection services)
{
services.AddControllers();
var contact = new OpenApiContact()
{
Name = "FirstName LastName",
Email = "user@example.com",
Url = new Uri("http://www.example.com")
};
var license = new OpenApiLicense()
{
Name = "My License",
Url = new Uri("http://www.example.com")
};
var info = new OpenApiInfo()
{
Version = "v1",
Title = "Swagger Demo API",
Description = "Swagger Demo API Description",
TermsOfService = new Uri("http://www.example.com"),
Contact = contact,
License = license
};
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", info);
}
}
Notice the code shown in bold letters. It creates three
Open API
objects - OoenApiContact, OpenApiLicense, and OpenApiInfo. The first two object
wrap information about Web API's contact person and license information. The
OpenApiInfo objects wraps these two objects. The AddSwaggerGen() call followed
by nested SwaggerDoc() call configures Swagger document generator by passing the
OpenApiInfo object.
Note that SwaggerDoc() method's first parameter indicates a name given to
this Swwagger document. You can call SwaggerDoc() multiple times to specify
multiple Swagger documents. The name in this case is v1 but you can use any
string value. This name is also used while configuring the Swagger middleware as
discussed next.
Modify the Configure() method as shown below:
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env)
{
...
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json",
"Swagger Demo API v1");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
The above code first calls UseSwagger() method followed by UseSwaggerUI()
method. The SwaggerEndPoint() method configures the Swagger end point by
specifying two things - URL to swagger.json and name to display in the document
selector (this will be clear shortly).
So far so good.
Now run the application by pressing F5. Once the browser window is opened, go
to the address bar and append /swagger to the URL. This will result in the
following Swagger UI.

The details such as contact, license, and description are displayed on this
page. Below you can invoke the API actions.
As an example click on the GET button to execute the Get() action. It will
render the following results.

You can also test other actions using this UI.
You can also configure Visual Studio to open the Swagger UI automatically
when the application starts. To do so, open project's properties page and click
on the Debug option. Then set the Launch browser value to swagger.

If you hit F5 again it will directly show the Swagger UI.
In the preceding example you created one Swagger document. That time it was
mentioned that you can define multiple documents. The following code from
ConfigureServices() and Configure() shows how that can be done.
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", info);
c.SwaggerDoc("v2", info2);
}
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json",
"Swagger Demo API v1");
c.SwaggerEndpoint("/swagger/v2/swagger.json",
"Swagger Demo API v2");
});
With these additions in place, the document selector dropdown list on the
Swagger UI will look like this:

As an ASP.NET developer using C# you are probably aware that C# and .NET Core
supports XML comments. If you add such XML comments to your Web API you might
want to show them onto the Swagger UI. To accomplish this task, first of all
enable XML comments in Visual Studio. You do this by opening project property
page's Build section.

As you can see above, the XML documentation file checkbox is checked and a
path of the file is mentioned in the associated textbox.
When you enable XML comments you might get warnings (green underlines) for
the methods in your app. You can get rid of these warnings by ignoring warning
number 1591. To do this go to the Errors and warnings section of the same page
and append 1591 at the end of existing warning levels.

Then go to the Get() action and add the following XML comments on top of it.
/// <summary>
/// Get All Messages
/// </summary>
/// <remarks>
/// Get() action returns all
/// the messages to the caller.
/// </remarks>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[]
{ "Hello World!",
"Hello Galaxy!",
"Hello Universe!"
};
}
Now, you need to tell Swagger to pick these XML comments. You do this in the
AddSwaggerGen() call in the ConfigureServices().
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", info);
var filePath = $"{Assembly.GetExecutingAssembly()
.GetName().Name}.xml";
filePath = Path.Combine(AppContext.
BaseDirectory, xmlFile);
c.IncludeXmlComments(filePath);
});
You basically compute the path of the file that stores the XML documentation.
Then you call IncludeXmlComments() method and pass that path to it.
The Swagger UI will now show these XML comments.

As you can see the Swagger UI is now reflecting the XML comments added to the
Get() action.
That's it for now! Keep coding!!