Test Your Endpoints Inside your ASP.NET Core Web API App with Swagger

7th October 2020

Testing your ASP.NET Core Web API endpoints is easy to do, thanks to Swagger.

Now I suspect a large number of you are familiar with Postman. Postman is a fantastic tool for testing out your API endpoints.

However, Postman has it's limitations!

Mainly that if you want to test out all your endpoints, you have to create them separately. And there is no way of getting Postman to show all the endpoints available in your API.

In-order to list out all your endpoints, you would have to do it inside your application. If only there was a package that allows you to do that?

Step aside Swagger. Swagger has been around for some years and you are able to integrate it into ASP.NET applications as well as ASP.NET Core.

By installing a NuGet package and making some configuration changes, you can view and test all your endpoints through your Web API application.

We are going to show you how to integrate it into an ASP.NET Core application.

How do we Install Swagger into our ASP.NET Core Application?

Assuming you already have an ASP.NET Core Web API setup with the endpoints you require, it's relatively straight-forward.

In Visual Studio, open up Package Manager Console and run the following command to install the Swagger NuGet package:

Install-Package Swashbuckle.AspNetCore

Now that we have that installed, we need to make some configuration changes in your Startup class.

Inside the ConfigureServices method, we need to add the AddSwaggerGen method from the IServiceCollection interface. Relatively straight forward.

After that, inside the Configure method, you need to add the UseSwagger and UseSwaggerUI methods that can be found inside the IApplicationBuilder interface.

You also need to declare the Swagger endpoint inside the UseSwaggerUI method.

The first parameter is an endpoint generated by Swagger. It basically lists all the endpoints available in JSON format.

The second parameter is declaring a name for your Swagger documentation.

// Startup.cs
public class Startup
{
	...	
	public void ConfigureServices(IServiceCollection services)
	{
		...

		services.AddSwaggerGen();
	}

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		app.UseSwagger();

		app.UseSwaggerUI(options =>
		{
			options.SwaggerEndpoint("/swagger/v1/swagger.json", "Round The Code");                           
		});

		...
	}
}

And that's it.

Run your ASP.NET Core Web API and point it to /swagger and you should see a list of endpoints available. You will also be able to test them by clicking on the appropriate endpoint.

Running Swagger in an ASP.NET Core Web API
Run your ASP.NET Core Web API and navigate to /swagger to see all your endpoints

What If I Want to Run Swagger on my ASP.NET Core Web API Home Page?

Just say, you want your list of API's to appear when the API loads up the home page.

All you need to do is to make a slight configuration change to the UseSwaggerUI method inside the IApplicationBuilder interface.

// Startup.cs
public class Startup
{
	...

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		...
		app.UseSwaggerUI(options =>
		{
			options.RoutePrefix = string.Empty;                
		});
		...
	}
}

Inside the options parameter, you can set a RoutePrefix. By default, this is set to swagger, but if you change it to string.Empty, it will run Swagger on the home page.

What If I Want to Override the Title on my Swagger Page?

Again, you need to make another configuration change to the UseSwaggerUI method inside the IApplicationBuilder interface.

// Startup.cs
public class Startup
{
	...

	// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
	{
		...
		app.UseSwaggerUI(options =>
		{
			options.DocumentTitle = "Round The Code";                
		});
		...
	}
}

Inside the options parameter, you can set the Title. This defaults to "Swagger UI", but you can override it by setting this parameter.

The title will then appear as your META title.

I Want to Display Comments in Swagger

First, you must make sure that all the endpoints that you wish to show comments for are marked up with a summary like below.

/// <summary>
/// Create an instance of League
/// </summary>
/// <param name="entity">The league entity</param>
/// <returns></returns>
public override Task<IActionResult> CreateAsync(League entity)
{
	...
}

Then it's a case of making some configuration changes.

As usual, we will be required to make a change inside the ConfigureServices method in the Startup class.

We already have added services.AddSwaggerGen() into our ConfigureServices method. Now, we need to extend it.

Make the following change to that method. This will read an XML file that has all our comments stored.

// Startup.cs
public class Startup
{
	...

	// This method gets called by the runtime. Use this method to add services to the container.
	public void ConfigureServices(IServiceCollection services)
	{
		...
		services.AddSwaggerGen(options =>
		{
			var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
			var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

			options.IncludeXmlComments(xmlPath);
		});
	}

	...
}

Now, if you were to run your ASP.NET Core Web API at this point, it will probably throw an error. Why is that?

It's because we have to include XML comments in your application when building it.

To do that in Visual Studio, right click on your Web API project and go to Properties.

Click on the Build tab, and you should see a tickbox that says XML documentation file. Make sure that is ticked.

Turn on XML documentation file to show comments in Swagger
Turn on XML documentation file to show comments in Swagger

Then, your comments should then appear on your Swagger page.

Comments Displayed in Swagger
Comments Displayed in Swagger

I Need to Remove Certain Endpoints from the Swagger Documentation

For that, you can use the [ApiExplorer] attribute.

Inside that attribute, you can set the IgnoreApi property. By default, it is set to false, but if you set it to true, it will hide it.

You can do this at action level to remove a certain endpoint, or do it at controller level to remove all the endpoints from that controller. Once applied, those endpoints no longer appear in the Swagger documentation.

// LeagueController.cs
[Route("api/league"), ApiExplorerSettings(IgnoreApi = true)]
public class LeagueController
{
	...
}

Where Can I See Swagger Installed?

As always, we've provided a video showing you how to install Swagger.

First, we will go ahead and install the Swashbucket.AspNetCore package into our ASP.NET Core Web API application. In addition, we will also add the necessary configuration changes to get the Swagger documentation working.

Next, we look at how we can change where the Swagger documentation is located in our application.

Afterwards, we look at ways for adding comments to our endpoints in the Swagger documentation.

Finally, we look at ways to remove certain API endpoints from the Swagger documentation.

What Security Aspects Should I Be Aware Of with Swagger?

In-terms of security on Swagger, it's fine running it on a local level, but you may need to consider removing it at production level. Otherwise, you could potentially be exposing all your API endpoints to the world.

In addition, it would be a good idea to lock down your API using OAuth security. Swagger does have the ability to allow you to set an access token to view your endpoints.

Swagger Is Great to Work Alongside Postman

I will personally use both Swagger & Postman for my API implementations.

Postman is a good tool to use if you don't want to expose your API implementation in your application. As I mentioned, there are plenty of times when this is the case.

But Swagger does make it easier to list all your endpoints and test them. And for that reason alone, I would recommend taking the time to implement it into your ASP.NET Core Web API application.

Want More ASP.NET Core Coding Tutorials?

Subscribe to my YouTube channel to get more ASP.NET Core coding tutorials.

You'll get videos where I share my screen and implement a how-to guide on a topic related to ASP.NET Core.

You can expect to see videos from the following technologies:

  • Blazor
  • Web APIs
  • SQL Server
  • Entity Framework
  • SignalR
  • and many more...

By subscribing, you can get access to all my ASP.NET Core coding tutorials completely free!

And so you never miss out on a new video, you have the option to be notified every time a new video is published.

So what are you waiting for?

To subscribe, click here to view my YouTube channel, and click on the red "Subscribe" button.

David Grace

David Grace

I am a .NET developer, building web applications in .NET Framework and .NET Core with a SQL Server database.

Some of the .NET packages I have used include Entity Framework and MVC.

I've also used many JavaScript frameworks such as React and jQuery, and have experience building CSS in SASS.

Twitter Feed