Learn and Understand How to generate Swagger.Json via MSBuild and .NET 8 with simple start up

Vamsi Dogiparthi
5 min readJul 8, 2024

--

Swagger+OpenAPI

Welcome programming buddy!! 😺 If you are in this article then definitely you are working on a use case where u have to generate swagger.json document during our post build process, which will be used during your deployment process in the pipeline. Along, with you might have also searched online and found out below things.

  1. NSwag official documentation is very vague and not enough. 😅
  2. To many places to search and still no straight answer with .NET 8. 😧

If you have faced above issues, then you were in the same boat as I was few weeks back and was scratching your head with frustration. But as you are reading this article, then you are not going to frustrate anymore as its going to provide you steps to complete this setup and will explain each every step in detail to understand the complete process. Sounds good! Lets get started then.

Create an empty .NET 8 (need to complete basic NSwag setup) or Download my presetup project from Github

To continue forward with our exercise please create an empty .NET 8 application and set it up with NSwag as shown in one of my article or download the pre setup project from this Github Repository.

Install NSwag.MSBuild Nuget Package.

In this step, we will be installing NSwag.MSBuild package to your project via Nuget package manager. I am providing you the command that needs to run in your package manager console.
Note: I am using version 14.0.8 for this exercise.

dotnet add package NSwag.MSBuild --version 14.0.8

Create swagger.json document via NSwag command.

In this step, we will create swagger.json document by running a NSwag command through powershell or package manage console in Visual Studio.

nswag new

This will create nswag.json file under your project route folder with default content. For this exercise we only need document generator section. So, you can remove the rest of the content and just keep the json as show below.

{
"runtime": "NetCore21",
"defaultVariables": null,
"documentGenerator": {
}
}

Note: the document generator section is responsible for defining the swagger.json document generation via MSBuild. We will modify the above json document to have more properties in it and will be going through each of the properties.

Modify the nswag.json file.

  1. Change the “runtime ”property in the json document to “Net80” as shown below. Which will set the runtime configuration of the current project to match with its target.
{
"runtime": "Net80",
"defaultVariables": null,
"documentGenerator": {
}
}

2. Add the below object “aspNetCoreToOpenApi” to the below json document. Among all the important setting are explained below with a comment. Hope that will help you understand its values and make sense out of them.

{
"runtime": "Net80", // defines the runtime for the project ex: Net80 (.NET8), Net50 (.NET 5), NetCoreApp31 (.NET Core 3.1)
"defaultVariables": null, // list of variables which will be used in the current json document with its default values
"documentGenerator": {
"aspNetCoreToOpenApi": {
"project": "MyFirstNSwagApplication.csproj", // path to your project file
"defaultUrlTemplate": "api/{controller}/{id?}",
"configuration": null, // configuration for the project such as Debug, Release etc.
"noBuild": true, // if true, the project will not be built before the generation
"verbose": true,
"requireParametersWithoutDefault": false,
"apiGroupNames": null,
"defaultPropertyNameHandling": "Default",
"defaultReferenceTypeNullHandling": "Null",
"defaultDictionaryValueReferenceTypeNullHandling": "NotNull",
"defaultResponseReferenceTypeNullHandling": "NotNull",
"generateOriginalParameterNames": true,
"defaultEnumHandling": "String", // a setting to define how enums are handled in the document ex: String, Integer
"flattenInheritanceHierarchy": false,
"generateKnownTypes": true,
"generateEnumMappingDescription": false,
"generateXmlObjects": false,
"generateAbstractProperties": false,
"generateAbstractSchemas": true,
"ignoreObsoleteProperties": false,
"allowReferencesWithProperties": false,
"useXmlDocumentation": true,
"resolveExternalXmlDocumentation": true,
"excludedTypeNames": [],
"serviceSchemes": [],
"infoTitle": "Arcade API Service", // document title
"infoDescription": "OpenAPI Specification for ArcadeService", // some document description
"infoVersion": "1.0.0", // version of the document
"documentProcessorTypes": [],
"operationProcessorTypes": [],
"useDocumentProvider": true,
"documentName": "v1", // name of the document
"aspNetCoreEnvironment": null, // environment for the asp.net core application ex: ASP_NETCOREENVIRONMENT = Development, Production etc.
"createWebHostBuilderMethod": null,
"startupType": null,
"allowNullableBodyParameters": true,
"useHttpAttributeNameAsOperationId": false,
"output": "OpenAPI/swagger.json", // path to the output file (which is our swagger.json file)
"outputType": "OpenApi3", // type of Swagger Open API output you are looking for
"newLineBehavior": "Auto",
"assemblyPaths": [],
"referencePaths": [],
"useNuGetCache": false
}
}
}

Change the MyFirstNSwagApplication.csproj XML file.

Now, we will be modifying the .csproj file of your project to include two parts to it as highlighted below with set of comments

<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<!-- Defines the build process to execute post build events defined below. -->
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="NSwag.AspNetCore" Version="14.0.8" />
<PackageReference Include="NSwag.MSBuild" Version="14.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>

<!-- Defines the Target for post build event and condition to be met inorder to be executed. -->
<Target Name="NSwag" AfterTargets="PostBuildEvent" Condition=" '$(Configuration)' == 'Debug' ">
<!-- A good practice to restore the project nuget packages to make sure the next step doesn't fail. -->
<Exec Command="dotnet tool restore"></Exec>
<!-- An exec command to generate swagger.json file as part of the build process.
EnvironmentVariables = allows you to set the project environment variable
WorkingDirectory = holds the directory path from which the command has to be executed
Command = holds the command to be executed when this exec block is executed during post build process
. -->
<Exec WorkingDirectory="$(ProjectDir)" EnvironmentVariables="ASPNETCORE_ENVIRONMENT=Development" Command="$(NSwagExe_Net80) run nswag.json" />
</Target>

</Project>

Build the .csproj file and look at the outcome:

Now, we will do the final step to build the .csproj file which should hopefully generate a new swagger.json file as specified in the nswag.json file or update if the file is already existing.
Note: Make sure you have Debug as your build setting.

succesfully executed the post build event
Created the swagger.json document.

Conclusion

Finally, we were able to generate the swagger.json during the MSBuild post build process. This will also keep your generated document upto date whenever you build your application and all the condition are met as per above configuration.

Hope this helps your use case. But as I said this a simple scenario with minimal program.cs file. In 90% of your projects I don’t think you will have such a simple program.cs to work with. So, I will be adding another article about how to include separate program.cs for only NSwag document generation so that your application build process won’t fail during your pipelines. Will keep you posted when the article is ready!!! 😃

Before if forget. Here is the Github repository Url used for the current exercise. See ya next time!!!!!

--

--