Using a ServiceReference in Blazor WebAssembly with System.Text.Json
A ServiceReference in C# allows you to access a swagger/open-api API from your C# project. This can be useful because the whole client to communicate with the API will be generated for you. It makes you think about the old WSDL days.
It will look like this in your CSPROJ
<ItemGroup> <OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" Namespace="ApiNamespace" ClassName="MyApiClient"> <SourceUri>https://URL_TO_API/swagger.json</SourceUri> </OpenApiReference> </ItemGroup>
Now using this API is as easy as this:
var httpClient = new HttpClient(); var client = new MyApiClient("URL_TO_API", httpClient); var response = await client.GetExampleAsync();
NSwag.ApiDescription.Client NuGet package will be used to generate the client. But this is only a development dependency and does not make your app any bigger.
System.Text.Json In Blazor WebAssembly projects, keeping the download size small is very important. Less dependencies means a smaller project size and a faster download and startup.
My advice is to use
System.Text.Json in a Blazor WebAssembly project. System.Text.Json is a high-performance, low-allocation JSON library that is included in the .NET Core runtime, so you don't need to add any additional dependencies to your project to use it.
By default, when you use a ServiceReference, it will use
Newtonsoft.Json (this adds about 1 MB to your WebAssembly project). By adding a small option, your client can be generation with
You can add this option to the generatior:
Ir will look like this:
<ItemGroup> <OpenApiReference Include="OpenAPIs\swagger.json" CodeGenerator="NSwagCSharp" Namespace="ApiNamespace" ClassName="MyApiClient" Options="/JsonLibrary:SystemTextJson"> <SourceUri>https://URL_TO_API/swagger.json</SourceUri> </OpenApiReference> </ItemGroup>
Enjoy your smaler WebAssembly app!