1.简单介绍
.NET9中Open Api有了很大的变化,在默认的Asp.NET Core Web Api项目中,已经移除了Swashbuckle.AspNetCore package,同时progrom中也变更为
builder.Servers.AddOpenApi()
builder.Services.MapOpenApi()
2025年微软将发布.NET10,OpenApi将会有一些enhancement,这边将尝试一下.NET10中Open Api的一些新特性。
2.具体说明
2.1 支持yaml格式
.NET10支持yaml格式的OpenApi文档,
2.1.1 创建项目并配置OpenAPI
1) 创建项目
2) Program中OpenApi相关代码变更为,
if (app.Environment.IsDevelopment())
{
app.MapOpenApi("/openapi/v3.yaml");
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/openapi/v3.yaml", "v3");
});
}
3) 添加的package reference如下,
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0-preview.3.25172.1" />
<PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="8.1.1" />
</ItemGroup>
2.1.2 运行一下
发现确实有yaml格式的Open Api文档生成,
1) 访问 https://localhost:<port>/swagger/index.html,界面如下图所示,
2) 访问yaml文档,地址是https://localhost:<port>/openapi/v3.yaml,界面如下图所示,
note, yaml格式的文档当前只能通过OpenAPI endpoint的形式访问到,比如
https://localhost:<port>/openapi/v3.yaml
后续微软可能还会添加一个新功能-build阶段生成yaml文档
2.2 支持添加Comment到OpenApi文档
2.2.1 创建项目并配置OpenAPI
1) 创建一个默认的Asp.NET Core Web Api项目,
2)在项目文件中添加<GenerateDocumentationFile>
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
3) 更新Progrom,
if (app.Environment.IsDevelopment())
{
app.MapOpenApi("/openapi/v1.json");
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/openapi/v1.json", "v1");
});
}
4)为Controller中的方法添加注释,如下图所示,
/// <summary>
/// Get Weather Data
/// </summary>
/// <remarks>
/// Generating random Weather Data
/// </remarks>
/// <returns>Random WeatherForecast data generated and returned from method Get </returns>
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get(){...}
2.2.2 运行一下
1)运行dotnet run
2) 访问对应的Open Api文档,发现<Summary>,<Remark>等相关的comment都已经输出到了OpenApi文档中了。
https://localhost:<port>/openapi/v1.json
note, 如果comment中有<parms>,也会包含到OpenApi文档中的。
2.3 Response description
当前ProducesResponseType增加了一个Description参数,这个参数也包含到OpenApi文档中
3.总结
本文简单尝试了一下.NET 10如下三个新特性
1) 支持yaml格式的OpenApi文档
2) 支持OpenApi中包含comment
3) ProduceResponseType中新增Description参数并支持导出到OpenApi文档。
当前大语言模型普及越来越广,其中Plugin/Function Calling是支持从Open Api文档转化成plugin的
await kernel.ImportPluginFromOpenApiAsync(
pluginName: "plugin01",
uri: new Uri("localhost:8080/swagger/v1/swagger.json"),
executionParameters: new OpenApiFunctionExecutionParameters() {
EnablePayloadNamespacing = true
}
);
同时微软的低代码平台Power Platform的custom connector也支持从OpenApi文档导入
微软在.NET10中对OpenApi做了进一步enhancement,这样就有了更完备的OpenApi文档,OpenApi与大语言模型相关应用或者Power Platform平台的整合将变得更加平滑。
2025年11月微软将发布.NET10,这是LTS(Long Term Support)版本。当前.NET10已经处于Preview3版本,新功能还在持续更新中,还需继续跟着微软学习一下。
本文如果哪里有错误,麻烦告之,谢谢谢谢!