從本篇開始,介紹一些很不錯的三方庫,來豐富MiniAPI的使用。
在建立MiniAPI項目時,模闆提供了一個是否啟用OpenAPI的選項,足見這個三方庫的優勢和強大。
OpenAPI為我們測試API提供了強大的支援,調用API的開發人員,可以輕松測試,參照開發接口和接口參數,有效的節省了大量文檔的書寫和調試流程複雜性。
為了更好的說明,需要開啟注釋檔案生成功能,打開項目檔案,增加GenerateDocumentdationFile節點即可。
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
</Project>
先看Swagger引入的代碼:
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo
{
Title = "MiniAPI08-V1",
Version = "v1"
}
);
//設定xml引用
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MiniAPI08.xml");
c.IncludeXmlComments(filePath);
//添加授權
var schemeName = "Bearer";
c.AddSecurityDefinition(schemeName, new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "請輸入不帶有Bearer的Token",
Name = "Authorization",
Type = SecuritySchemeType.Http,
Scheme = schemeName.ToLowerInvariant(),
BearerFormat = "JWT"
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement {
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = schemeName
}
},
new string[0]
}
});
});
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.EnablePersistAuthorization();
});
}
app.MapPut("/test", (Data data) =>
{
})
.WithName("puttest")
.WithTags("all test");
app.MapDelete("/test/{id}", TestHandle.DeleteTest)
.WithName("deletetest")
.WithTags("all test");
app.MapGet("/test/{id}", (HttpRequest request, int id) =>
{
Console.WriteLine(request.Headers["Authorization"]);
})
.WithName("gettest")
.WithTags("all test")
.Produces<Data>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);
app.MapPost("/test", (Data data) =>
{
})
.WithName("posttest")
.WithTags("all test");
app.Run();
class TestHandle
{
/// <summary>
/// 删除Test
/// </summary>
/// <param name="id">Data的主鍵</param>
/// <returns></returns>
public static bool DeleteTest(int id)
{
return true;
}
}
/// <summary>
/// 送出資料
/// </summary>
class Data
{
/// <summary>
/// 編号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 名稱
/// </summary>
public string Name { get; set; }
}
Tags 是all test,可以把同類操作放在一個組裡,對應着swagger的一組
現在的MiniAPI對單個請求還不支援注釋(就是get ,post,put,delete的api注釋),相信.NET 7會解決掉。
如果請求的方法是匿名方法,同樣參數也是不支援說明的,如果像delete請求,指像命名方法,方法的參數是注釋說明是會顯示在swagger裡的:
如查Mini API支援Token驗證,可以通過AddSwaggerGen添加Security來實作自帶Token,具體做法見代碼實作:c.AddSecurityDefinition和 c.AddSecurityRequirement。這樣可以在Swagger頁面,點選Authorize按鈕,輸入Token,這時,所有的請求都會帶上Authorization的header。
調用Get方法時,會自動帶上Authorization
後端會擷取到Token資料