NSwag Tutorial: Integrate the NSwag toolchain into your ASP.NET Web API project

https://blog.rsuter.com/nswag-tutorial-integrate-the-nswag-toolchain-into-your-asp-net-web-api-project/

This tutorial shows how to integrate NSwag (Swagger toolchain for .NET) so that you can access your Web API actions with the Swagger UI and a generated C# client library.

The toolchain can be integrated into the following three types of Web API projects:

  • Global.asax-based Web projects (full .NET Framework)
  • OWIN-based Web projects (full .NET Framework)
  • ASP.NET Core based projects (full .NET Framework or .NET Core)

For each project, the integration is a little bit different, but this tutorial will provide links to all supported ways. Just follow the steps.

1. Create and setup a new Web API project

First we implement your Web API project:

  1. Open Visual Studio and create a new Web API project (either Global.asax-, OWIN- or ASP.NET Core-based).
  2. Register the NSwag Swagger middlewares:
  3. (optional) Globally register the Web API exception serialization filter

 

2. Run the Web API project

Run the project and navigate to the URL http://yourserver/swagger: Here you should see the Swagger UI.

Try calling your Web API actions and check the results.

3. Generate client code to access the Web API

The next steps show how to generate a client library to access the Web API actions in the Web project. In this tutorial we use the C# client generator (there is also a TypeScript client generator).

Setup tooling and create client project:

  1. Install NSwagStudio.
  2. Create a new C# library project in your solution (the service client library).
  3. Add the required assembly dependencies to the library project.

Generate code:

  1. Start NSwagStudio and select “Swagger Specification” as input.
  2. Enter the Swagger specification URL (default: http://yourserver/swagger/v1/swagger.json, the server must be running).
  3. Click “Generate Outputs” and select the tab “CSharpClient”.
  4. Copy the source code into your client project.
  5. Now you should change generator settings in the NSwagStudio to improve and customize the generated code (e.g. define the correct namespace, etc.). 

Automate script generation:

  1. Save the .nswag file in NSwagStudio
  2. Open a command prompt and cd to the directory with the .nswag file
  3. Run nswag run to execute all .nswag files (the NSwag command line tool is automatically registered by the MSI installer)

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(506)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2018-01-24 Code Coverage and Unit Test in SonarQube
点击右上角即可分享
微信分享提示