Understand & Setup .NET 8 application with NSwag together

Vamsi Dogiparthi
7 min readJul 2, 2024

--

Swagger+OpenAPI

Together!!!!? Yes, you heard it right. We are going to understand, build a .NET 8 application and setup NSwag together as program buddies 😍. You might have read multiple articles, different way of explaining things. My articles are little different as I am not an expert instructor but a curious programmer like you. Who knows the pain of doing something new, issues with writing code without understanding it first and finally becoming miserable. So, in this article I will take you through the NSwag setup step by step with explanation about what each step is doing and what is the outcome of it, in a simple plain language (not in a philosophical way). 😜

Excited! Lets start our journey together.

NSwag:

If you are new coder, starting to build web application using .NET 8 or old programmer working on a bunch of web applications through your daily life and trying to upgrade your .NET application to .NET 8. You might have heard about NSwag. If not, no worries! Let me explain it in a simple language. NSwag is an Open Source OpenAPI nuget library developed/sponsered by Rico Suter. OpenAPI? 😕. No worries, I am going to write a different article about OpenAPI. To understand it much better. But for now, in a simple language, OpenAPI is a specification document to share your REST APIs publicly and freely with your consumers, allowing them easily understand the metadata of your endpoints and provide them enough instructions to invoke them successfully via code or through UI. Sounds interesting isn’t it? Yes, it is very interesting and useful.

Now, lets get back to NSwag which is now the recommended Open API toolset recommended and soon will be defaulted over other toolsets starting .NET 8 and higher applications. No more Swashbuckle! There are some official documents from both Microsoft and NSwag author on Github. Which might give you some good information, buttt! they are not complete. Especially NSwag github articles. They are so vague and scattered, trust me as your use case gets complex, thus finding straight forward documentation on NSwag.

Sounds 😟? No problem. As a programming buddy, I got your back. In this article and following articles. I will take you through some simple, moderate use cases that you can solve with my NSwag setup process easily. So, Ready! Then lets get started!

Step 1: Creating a simple .NET 8 Web application using Visual Studio

  1. Download & Install latest 2022 visual studio from Microsoft official website. The link I provided is for Community Edition. Which is free and enough for all our test cases.
    Note: Choose .NET 8 SDK, .NET web development while downloading and installing the Visual Studio
  2. After you have installed Visual Studio. Please create new .NET 8 Web Application as shown below.
Project Creation process

After selecting the project type as shown above. Click next and give it a name as shown below

Project configuration

Now, choose framework and defaults for all the options as shown below and click on create.

Project framework and other creation defaults

Now if you inspect your solution explorer the installed packages, you will find swashbuckle which is installed by default into the project. This is because of the Enable Open API support option we chose as per above image. We will be removing this and other connected code from program.cs. We will then install NSwag nuget packages from Package manager console, will initialize respective methods in the program.cs. To make it work with NSwag

Step 2: Removing Swashbuckle Code from program.cs & an Swashbuckle nuget package

Now as per our plan lets inspect and remove swashbuckle code from program.cs and unintall Swashbuckle nuget.

  1. Uninstall swashbuckle nuget. Yes, we will first uninstall the package, which is personally easiest way to find the code which is using this package and remove it easily. To uninstall, just go to nuget package manager in your visual studio and uninstall it as shown below
Finding nuget Package manager console
Instruction to uninstall swashbuckle.

2. Now, once you have uninstalled the package. If you build your application from build menu. You will that it will fail with errors in program.cs file. Which is the easy way to remove the connected code from the project. Refer to the below images and code snippets. We are just going to remove the lines which are throwing error from the program.cs file

Before removing error code.
After removing swashbuckle code.

Now, build the application and it shouldn’t throw any error! Yahh! We have successfully removed Swashbuckle and related code from our project. Now its time for us to install the required NSwag nugets. Lets do it in the next step.

Step 3: Installing NSwag Nuget

In this section lets install two NSwag Nuget packages required for our project.

  1. Install NSwag.AspNetCore: Go to Tools -> Nuget Package Manager -> Package Manager for Solution -> Browse -> Enter “NSwag.AspNetCore”. Select the package, project and install it.
Nuget search

Step 4: Modify the Program.cs

Now, as we installed the required package we will be adding below code to the program.cs

Three methods which allows you to configure NSwag in your program.cs

  1. builder.Services.AddOpenApiDocument(): A Service extension method built and shipped with NSwag nuget package. Which allows you to start generating Open API document to your application, which will be later used and hosted on our localhost or deployed app service at a default URI (customizable)
    Note: The Open API generation code, looks into your controllers, HTTP methods initialized to generate a JSON spec document automatically.
  2. app.UseOpenApi(): A NSwag middleware shipped as part of the NSwag nuget we installed, which will allow us to host the generated Open API
    Note:
    default hosted local url: http://localhost:{portnumber}/swagger/v1/swagger.json
  3. app.UseSwaggerUi(): This extension method is to host the prebuilt Swagger UI which uses your swagger.json created/hosted by previous methods into an intutive UI, which can be used to test your API endpoints from the browser and also provide visual information about your end point Metadata. Such as type of Endpoint (POST, PUT, GET, DELETE), Object Schema that endpoint expects and their details such as data type of the object attributes, required vs non required fields etc.
    Note:
    default hosted local url: http://localhost:{portnumber}/swagger/index.html
// Add services to the container.
builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
// An extension method to add the nSwag open api document generation service from NSwag
builder.Services.AddOpenApiDocument();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
// an web application middleware method to allow you
// to use the nSwag open api generated swagger json document
// default hosting local url: http://localhost:{portnumber}/swagger/v1/swagger.json
app.UseOpenApi();
// an web application middleware method to allow you to use the
// nSwag prebuilt swagger ui to interact with your apis from the browser
// default hosting local url: http://localhost:{portnumber}/swagger/index.html
app.UseSwaggerUi();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 5: Build and Run the application.

As we did all the required setup. Let’s build, run the application and visit both the swagger document hosted url and swagger ui.

for your reference Github Repository to the code that we just wrote together.

Conclusion:

Yahhh! 😆. We finally did the setup of the NSwag for our .NET 8 application together and one of the most important factor is we understood, each and every step required to finish this process. Ufff! Done!!!

Not Yet! As I said this is a simple use case, but not everytime in our daily life things will be this simple and none of the applications I worked on have such a simple program.cs. Sounds Scary! 😱. No worries! In the next articles I will take you through some important concepts such as Customizing your NSwag UI and document hosting URI, customizing some of the NSwag document metadata such as document title, version etc. After that we will go through how to solve object customization, type mappers (from some know issues of swagger), generating swagger spec document via MSBuild to deploy it through your pipelines or share it with some cloud API management services like Azure APIM etc.

--

--