OpenApiReference is a project-file element that connects an OpenAPI document to C# client generation. It identifies the document, generator, namespace, and generated client class. section 11.4.1
A typical configuration specifies:
- Include: the local OpenAPI document, such as OpenAPIs\swagger.json. section 11.4.1
- CodeGenerator: NSwagCSharp for generating the C# client. section 11.4.1
- Namespace and ClassName: the namespace and class name used by generated code. section 11.4.1
- SourceUri or SourceUrl: the address from which the OpenAPI JSON is obtained, depending on the setup. section 11.4.1 section 11.4.2
Customize generated client code
Add an Options element to select System.Text.Json, generate an interface, and place the API base address on HttpClient: <Options>/UseBaseUrl:false /GenerateClientInterfaces:true /JsonLibrary:SystemTextJson</Options>. The resulting client can implement IFruitClient and call FruitPOSTAsync and FruitGETAsync. section 11.4.4
Listing 11.3 Adding a service reference for OpenAPI client generation with Visual Studio
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<OpenApiReference #1
Include="OpenAPIs\swagger.json"
CodeGenerator="NSwagCSharp"
Namespace="Fruit"
ClassName="FruitClient">
<SourceUri>https://localhost:7186/swagger/v1/swagger.json</SourceUri>
</OpenApiReference>
</ItemGroup>
<ItemGroup>
<PackageReference #2
Include="Microsoft.Extensions.ApiDescription.Client"
Version="3.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers;
buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NSwag.ApiDescription.Client"
Version="13.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers;
buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
#1 Defines where the OpenAPI description was loaded from and code generation settings
#2 Extra NuGet packages are required by the code generator.
Inspect the complete project-file configuration, including the OpenApiReference element and supporting package references. section 11.4.1
