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:
- Open Visual Studio and create a new Web API project (either Global.asax-, OWIN- or ASP.NET Core-based).
- Register the NSwag Swagger middlewares:
- Global.asax: Register the OWIN Middlewares in your Global.asax.
- OWIN and ASP.NET Core: Register the OWIN or ASP.NET Core Middlewares in your Startup.cs.
- (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:
- Install NSwagStudio.
- Create a new C# library project in your solution (the service client library).
- Add the required assembly dependencies to the library project.
Generate code:
- Start NSwagStudio and select “Swagger Specification” as input.
- Enter the Swagger specification URL (default:
http://yourserver/swagger/v1/swagger.json
, the server must be running). - Click “Generate Outputs” and select the tab “CSharpClient”.
- Copy the source code into your client project.
- 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:
- Save the
.nswag
file in NSwagStudio - Open a command prompt and
cd
to the directory with the.nswag
file - Run
nswag run
to execute all.nswag
files (the NSwag command line tool is automatically registered by the MSI installer)
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.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