Minimal Web API 介紹
以前在用 Flask 時,覺得它真的是小巧好用,如果只是寫個簡單的 API,Flask 是個好選擇。但在 ASP.NET MVC 上因為專案的架構,在寫簡單的專案時會覺得有點用牛刀的感覺。不過在 .NET 6 中有個 Minimal Web API 可用,它可以讓你把所有的程式碼都寫在 Program.cs 檔上,前提是你的功能不大。以下簡介如何使用方式:
首先開一個 ASP.NET Core Web API 專案
記得把控制器這個選項取消
專案產生後,會發現架構非常之簡單,一個 Program.cs 跟一個設定檔
打開 Program.cs 後,會發現前面幾行的程式碼
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseFileServer();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
專案中已經替你準備好 Swagger UI 來測試 API,如下圖
這時來寫自己的 API,功能很單純,只是從設定檔取值並回傳,程式碼如下
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"TestSection": "aaa4"
}
app.MapGet("/TestConfig", () =>
{
string result = builder.Configuration.GetSection("TestSection").Value;
return result;
});
測試結果如下
最後寫一個 POST 的 API,程式碼如下
app.MapPost("/TestJson", (PostData data) =>
{
return Results.Json(data);
});
internal class PostData
{
public int aaa3 { get; set; }
public string aaa4 { get; set; } = string.Empty;
}
測試 UI 很貼心的把測試資料準備好,修改一下值就可以測了
參考資料