This tutorial shows how to generate an Angular TypeScript client with the NSwag Swagger toolchain. You can use this client in your Angular 2 SPA (single-page application) to consume the web services of an existing Web API project. The metadata for the client generator will be loaded from an existing .NET assembly which contains your Web API controller classes. The NSwag project provides many other TypeScript templates (for targeting other JS frameworks) and also a C# client generator.
For ASP.NET Core projects, I recommend to use the middleware to generate the Swagger spec (there are some problems loading .NET Core assemblies via reflection). If you want to try to load your .NET Core assembly via reflection, you also need to specify a reference path.
1. Configure the input
Let’s install the tooling and create a new base project:
- Install NSwagStudio.
- Start NSwagStudio, create a new
.nswagdocument and select Web API Assembly as input.
- Select an assembly (.dll) containing your Web API controllers from the web host project’s build output (all required assemblies must be available).
- Select the
Web.configof your Web API host project.
- Now click on the “Load Assemblies” button which searches for controllers in the selected assembly (or assemblies).
- Select the controller classes for which you want to generate a TypeScript client:
2. Configure the output
The client generator can be configured in many ways – we will mostly use the defaults:
- On the right side of the window you can see the available output tabs: Select “TypeScript Client”.
- In the settings, change the Template setting to
3. Generate client code
The next step is to finally generate code:
- Click on “Generate Outputs” and shortly the generated TypeScript code appears
- Copy the generated code into your Angular 2 project and start accessing your Web API from Angular 2
But there is always more: You can extend the generated TypeScript classes with custom code
Tags: Angular 2, ASP.NET, Code Generation, NSwag, Swagger, Web API