在.NET9的第4個預覽版裏,微軟帶來了OpenAPI,需要參照 Microsoft.AspNetCore.OpenApi,如果想生成原生的API描述檔,需要參照 Microsoft.Extensions.ApiDescription.Server。
下面是計畫檔:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.0-preview.4.24267.6" />
<PackageReference Include="Microsoft.Extensions.ApiDescription.Server" Version="9.0.0-preview.4.24267.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<PropertyGroup>
<OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
<OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
</PropertyGroup>
</Project>
使用OpenApi只需要在用Services.AddOpenApi()和app.MapOpenApi(),即可。也可以透過AddOpenApi的參數Action,來改變或完善API配置資訊,具體程式碼如下:
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging.Configuration;
using Microsoft.OpenApi.Extensions;
using Microsoft.OpenApi.Interfaces;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi("myapi", opt =>
{
opt.UseTransformer((oper, context, c) =>
{
oper.Info = new OpenApiInfo
{
Version = "v1",
Title = "My API",
Description = "My API Description",
Contact = new OpenApiContact
{
Name = "My Name",
Email = "[email protected]"
},
License = new OpenApiLicense
{
Name = "MIT",
Url = new Uri("https://opensource.org/licenses/MIT")
},
TermsOfService = new Uri("https://www.google.com"),
};
return Task.CompletedTask;
});
opt.ShouldInclude = (o) =>
{
Console.WriteLine("-----HttpMethod------" + o.HttpMethod);
Console.WriteLine("-----GroupName------" + o.GroupName);
Console.WriteLine("------RelativePath-----" + o.RelativePath);
Console.WriteLine("------ActionDescriptor-----" + o.ActionDescriptor.DisplayName);
returntrue;
};
opt.UseOperationTransformer((oper, context, c) =>
{
Console.WriteLine("======summary=======" + oper.Summary);
oper.Summary = "gui su wei test summary";
oper.Tags = new OpenApiTag[]
{
new OpenApiTag
{
Name = "tag1", Description = "tag1 description",
},
new OpenApiTag
{
Name = "tag2", Description = "tag2 description",
}
};
return Task.CompletedTask;
});
});
var app = builder.Build();
app.MapOpenApi("/openapi/{documentName}.json");
app.MapGet("/order", () =>
{
returnnew Order()
{
OrderNo = "20210901",
Amount = 100,
OrderDate = DateTime.Now
};
});
app.MapPost("/order", (Order order) =>
{
returnnew OkResult();
});
app.Run();
///<summary>
/// 訂單
///</summary>
public classOrder
{
///<summary>
/// 訂單編號
///</summary>
publicstring OrderNo { get; set; }
///<summary>
/// 訂單金額
///</summary>
publicdecimal Amount { get; set; }
///<summary>
/// 訂單日期
///</summary>
public DateTime OrderDate { get; set; }
}
下面是執行的結果:
可以透過存取http://localhost:5287/openapi/myapi.json,來檢視api的json資訊,同時,也可以檢視生成的api.json檔, 因為我們配置了api檔的生成,結果都一樣,如下:
{
"openapi": "3.0.1",
"info": {
"title": "My API",
"description": "My API Description",
"termsOfService": "https://www.google.com",
"contact": {
"name": "My Name",
"email": "[email protected]"
},
"license": {
"name": "MIT",
"url": "https://opensource.org/licenses/MIT"
},
"version": "v1"
},
"paths": {
"/order": {
"get": {
"tags": [
"tag1",
"tag2"
],
"summary": "gui su wei test summary",
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"orderNo": {
"type": "string"
},
"amount": {
"type": "number",
"format": "double"
},
"orderDate": {
"type": "string",
"format": "date-time"
}
}
}
}
}
}
},
"x-aspnetcore-id": "e8ba784f-bc44-4d62-9132-2e0ec46472ea"
},
"post": {
"tags": [
"tag1",
"tag2"
],
"summary": "gui su wei test summary",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"orderNo": {
"type": "string"
},
"amount": {
"type": "number",
"format": "double"
},
"orderDate": {
"type": "string",
"format": "date-time"
}
}
}
}
},
"required": true
},
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"statusCode": {
"type": "integer",
"format": "int32"
}
}
}
}
}
}
},
"x-aspnetcore-id": "ddb8949d-07dc-414a-99b0-a298aab0ecb8"
}
}
},
"tags": [
{
"name": "OpenAPIDemo"
}
]
}