我想使用Swashbuckle.AspNetCore.Cli
和SwaggerHostFactory
来生成swagger.json。
对于path
和compoments
,生成的swagger.json总是空的,这很奇怪。
创建项目
dotnet new webapi -o DemoWebApi
cd DemoWebApi
dotnet restore
示例
- DemoWebApi.csrpoj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>
<!-- create openapi cli -->
<Target Name="OpenApiCliBuild" AfterTargets="PostBuildEvent" Condition="'$(Configuration)' == 'Debug'">
<!-- create static file openapi doc -->
<Exec Command="dotnet tool restore" />
<Exec Command="dotnet new tool-manifest --force" />
<Exec Command="dotnet tool install --local Swashbuckle.AspNetCore.Cli --version 6.4.0" />
<Exec Command="dotnet swagger tofile --output swagger.json $(OutputPath)\$(AssemblyName).dll v1" />
</Target>
</Project>
- C#程式码
// SwaggerHostFactory.cs
public class SwaggerHostFactory
{
public static IHost CreateHost()
{
var builder = WebApplication.CreateBuilder();
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
return app;
}
}
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// ignore... same as SwaggerHostFactory
app.MapControllers();
app.Run();
运行项目
dotnet watch run
预期输出
- 如果未使用SwaggerHostFactory
{
"openapi": "3.0.1",
"info": {
"title": "DemoWebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
"version": "1.0"
},
"paths": {
"/WeatherForecast": {
"get": {
"tags": [
"WeatherForecast"
],
// ...ignore
}
}
}
,
"components": {
"schemas": {
"WeatherForecast": {
"type": "object",
// ...ignore
}
}
}
}
实际输出
- 使用SwaggerHostFactory
{
"openapi": "3.0.1",
"info": {
"title": "dotnet-swagger",
"version": "1.0"
},
"paths": { },
"components": { }
}
Swashbuckle.AspNetCore.Cli
是否支持使用SwaggerHostFactory
int .NET 6?我该怎么做?
1条答案
按热度按时间p5fdfcr11#
最后我放弃了使用
ASP.NET Core 6 top-level statements
,使用了SwaggerHostFactory
的旧风格,效果很好。不过我想别人可能会有更好的办法。