我在 .NET 用過 Swashbuckle(已停止更新)、Swagger-NET(fork Swashbuckle),在 .NET Core,已經不適用了,同時支援 ASP.NET Core 及 OWIN Middleware,通吃 .NET Framework 與 .NET Core 版本的 WebAPI,該是時候準備換掉了...
ASP.NET Core Middleware
開發環境
- VS 2019
- .NET Framework 4.5
開一個 ASP.NET Core Web Application 專案 → 範本 API
安裝套件
Install-Package NSwag.AspNetCore
Startup.cs
配置 Middleware
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
// Add OpenAPI/Swagger middlewares
app.UseOpenApi(); // Serves the registered OpenAPI/Swagger documents by default on `/swagger/{documentName}/swagger.json`
app.UseSwaggerUi3(); // Serves the Swagger UI 3 web ui to view the OpenAPI/Swagger documents by default on `/swagger`
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// Add OpenAPI v3 document
services.AddOpenApiDocument();
// Add Swagger v2 document
// services.AddSwaggerDocument();
}
參考:https://github.com/RicoSuter/NSwag/wiki/AspNetCore-Middleware
專案位置:https://github.com/yaochangyu/sample.dotblog/tree/master/WebAPI/NSwag/Lab.NSwagDoc/WebApiCore31
ASP.NET OWIN Middleware
開發環境
VS 2019
.NET Framework 4.5
開一個 ASP.NET Web Application 專案 → 範本 Web API
安裝套件
Install-Package NSwag.AspNet.Owin
Install-Package Microsoft.AspNet.WebApi.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
在 Web.config 配置 module 或 handler
以下兩種方法擇一使用
將所有請求通過 Pipe(管道)傳遞到.NET管道
在 system.webServer
節點,設定 runAllManagedModulesForAllRequests
= true
以便所有的請求通過 Pipe 傳送到 ASP.NET
<system.webServer>
...
<modules runAllManagedModulesForAllRequests="true"></modules>
...
僅將 Swagger 請求傳送到特定的中間件
在 web.config
的 UseSwagger/UseSwaggerUi
節點,增加以下設定
<system.webServer>
...
<handlers>
...
<add name="NSwag" path="swagger" verb="*"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
Startup
配置 Middleware,官方文件上面用已經過期的 UseSwaggerUi,這裡我改用 UseSwaggerUi3
public class Startup
{
public void Configuration(IAppBuilder app)
{
//var config = new HttpConfiguration();
var config = GlobalConfiguration.Configuration;
app.UseSwaggerUi3(typeof(Startup).Assembly,
settings =>
{
settings.GeneratorSettings.DefaultUrlTemplate =
"api/{controller}/{id?}";
settings.PostProcess = document =>
{
document.Info.Title =
"WebAPI OWIN Demo";
};
});
//app.UseWebApi(config);
//config.MapHttpAttributeRoutes();
config.EnsureInitialized();
}
}
參考:https://github.com/RicoSuter/NSwag/wiki/OWIN-Middleware
ASP.NET Global.asax OWIN Middleware
開發環境
VS 2019
.NET Framework
開一個 ASP.NET Web Application 專案 → 範本 Web API
安裝套件
Install-Package NSwag.AspNet.Owin
Install-Package Microsoft.Owin.Host.SystemWeb
在 Web.config 配置 module 或 handler
請看上一章節的配置 #在 Web.config 配置 module 或 handler
在 Global.asax 增加 OWIN 的配置
protected void Application_Start()
{
RouteTable.Routes
.MapOwinPath("swagger", app =>
{
app.UseSwaggerUi3(typeof(WebApiApplication).Assembly,
settings =>
{
settings.MiddlewareBasePath = "/swagger";
settings.GeneratorSettings
.DefaultUrlTemplate =
"api/{controller}/{id}";
settings.PostProcess = document =>
{
document.Info.Title =
"WebAPI NSwag";
};
});
});
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
停用 OWIN Startup.cs
owin:AutomaticAppStartup
= true
<appSettings>
....
<add key="owin:AutomaticAppStartup" value="false" />
</appSettings>
參考:https://github.com/RicoSuter/NSwag/wiki/OwinGlobalAsax
專案位置:https://github.com/yaochangyu/sample.dotblog/tree/master/WebAPI/NSwag/Lab.NSwagDoc/WebApi2.IIS.NET45
Console OWIN Middleware
開發環境
VS 2019
.NET Framework
開一個 Console Application 專案
安裝套件
Install-Package NSwag.AspNet.Owin
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Install-Package Microsoft.Owin.Diagnostics
Install-Package Microsoft.Owin.Host.SystemWeb
Startup.cs
配置 Web API Routing、Middleware
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
app.UseSwaggerUi3(typeof(Startup).Assembly,
settings =>
{
settings.GeneratorSettings.DefaultUrlTemplate =
"api/{controller}/{id?}";
settings.PostProcess = document =>
{
document.Info.Title =
"WebAPI OWIN Demo";
};
});
WebApiConfig.Register(config);
app.UseErrorPage();
app.UseWelcomePage("/Welcome");
app.UseWebApi(config);
config.EnsureInitialized();
}
}
Web API Route 設定
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
訪問 Swagger
瀏覽 Swagger 文件與與 Swagger UI 頁面,預設位置為
Swagger UI:/swagger
Swagger 規格:/swagger/v1/swagger.json
例如:https://localhost:5001/swagger/
產生 Client Proxy 程式碼
之前寫過的方法
https://dotblogs.com.tw/yc421206/2019/01/23/tips_write_write_web_api_document_via_swagger#Code%20Gen
官方提供以下方法:from https://github.com/RicoSuter/NSwag/wiki
Automated
CLI:
- Run as part of the MSBuild process
- Command Line (via NPM or MSI Installer)
- (T4 templates) (outdated, not recommended)
GUI:
- NSwagStudio (Windows GUI)
- Edit .nswag configuration files which can be executed via command line
- Swagger/OpenAPI specification via URL or from a .NET assembly (no running web app needed)
Manual:
- TypeScriptClientGenerator: Generate TypeScript clients
- CSharpClientGenerator: Generate CSharp clients
- CSharpControllerGenerator: Generate CSharp Web API controllers (contract first/schema first development)
啟用專案註解
我習慣在不同的 build 輸出,指定相同的位置,對 CI 的配置而言會比較簡單
文件撰寫
C# 裡面把註解寫好,掛上 Attribute,NSwag 就會根據註解長出對應的 UI,官方文件如下
- AspNetCoreOpenApiDocumentGenerator (ASP.NET Core only):
- Generate a Swagger/OpenAPI specification from ASP.NET Core controllers via API Explorer
AddOpenApiDocument()
,AddSwaggerDocument()
, etc.UseOpenApi()
,UseSwaggerUi3()
,UseReDoc()
, etc.
- WebApiOpenApiDocumentGenerator (supports ASP.NET and ASP.NET Core, deprecated):
- Generate a Swagger specification for Web API controller classes (Reflection based):
UseSwagger()
,UseSwaggerUi3()
, etc.- Assembly loading instructions (required for CLI usage)
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET