Skip to main content

How to add Swagger to ASP.NET Core 6 Application

Swagger is very popular and doesn’t need an introduction. It helps you to test your API. Earlier, I posted about how to add Swagger to ASP.NET Core 2.0 web API and those steps still works for ASP.NET Core 5 based applications where you bring Swashbuckle nuget packages and then add code to Startup.cs file to enable Swagger. But with ASP.NET Core 6, things have become a little easy and time saving. Now you can easily add swagger to ASP.NET Core 6 application with a mouse click.

Add Swagger to ASP.NET Core 6 Application

Visual Studio 2022 allows you to add Swagger to ASP.NET Core 6 app, at the time of creating a ASP.NET Core 6 project. Visual Studio 2022 project creation wizard has an option “Enable OpenAPI support”, which is enabled by default. This option ensures that all the swagger related nuget packages are installed and the required code to enable swagger is in place in the Program.cs.

Why Program.cs? Because with ASP.NET Core 6.0 Startup.cs and Program.cs files are now combined for unified experience. But, if you like Startup.cs then you can add back Startup.cs in ASP.NET Core 6.

Take a look at below screenshot of project creation with VS 2022. As you can see, the option “Enable OpenAPI support” is checked.

Add Swagger to ASP.NET Core 6 App

If you take a look at Program.cs, you’ll find Swagger related code is already placed. The Swagger service is registered and middleware is added for development environment. You will find in Solution explorer that Swashbuckle nuget package is also installed for you.

Add Swagger to ASP.NET Core 6 App

Without doing anything, if you run the app it will open the Swagger UI for the WeatherForecast API.

Add Swagger to ASP.NET Core 6 App

But how come it is directly going to Swagger UI URL? Well, it is going there because of "launchUrl": "swagger" is set in the launchsettings.json file.

That’s it.

[UPDATE: One of my blog reader pointed out that the option Enable OpenAPI support is also available with VS 2019 only when you select .NET 5 from the Target Selection Framework. It’s not available with other framework version.]

Thank you for reading. Keep visiting this blog and share this in your network. Please put your thoughts and feedback in the comments section.

PS: If you found this content valuable and want to return the favour, then Buy Me A Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *