Rico Suter's blog.
 

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.

Introduction video:

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:

  1. Install NSwagStudio.
  2. Start NSwagStudio, create a new .nswag document and select Web API Assembly as input.
  3. Select an assembly (.dll) containing your Web API controllers from the web host project’s build output (all required assemblies must be available).
  4. Select the Web.config of your Web API host project.

  1. Now click on the “Load Assemblies” button which searches for controllers in the selected assembly (or assemblies).
  2. 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:

  1. On the right side of the window you can see the available output tabs: Select “TypeScript Client”.
  2. In the settings, change the Template setting to Angular2:

3. Generate client code

The next step is to finally generate code:

  1. Click on “Generate Outputs” and shortly the generated TypeScript code appears
  2. 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



Discussion