Minimal API Todo Sample
Minimal API Todo Sample
Intro
.NET 6 Preview 4 開始引入了 Minimal API 到如今的 RC1,Minimal API 也完善了許多并且修復(fù)了很多BUG,之前也寫過文章介紹,可以參考:ASP.NET Core 6 Minimal API ,不過只是寫了一個(gè) Hello World, 最早還要 Using 現(xiàn)在默認(rèn)啟用了隱式命名空間可以不用在代碼里寫 using 了,今天就來用 Minimal API 來寫一個(gè)簡單的增刪改查的 Todo API,一起來看下面的示例吧
Sample
下面的這個(gè)小示例,除了基本的增刪改查 API 還包含了 swagger 的配置、 EF Core 的使用以及認(rèn)證授權(quán)
示例代碼如下:
var?builder?=?WebApplication.CreateBuilder(args);//?注冊?DbContext builder.Services.AddSqlite<TodoDbContext>(builder.Configuration.GetConnectionString("Todo")); //?注冊?swagger builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(c?=> {c.SwaggerDoc("v1",?new()?{?Title?=?"MinimalTodoAPI",?Version?=?"v1"?}); }); //?注冊認(rèn)證授權(quán) builder.Services.AddAuthentication(QueryAuthenticationDefaults.AuthenticationSchema).AddQuery(); builder.Services.AddAuthorization();var?app?=?builder.Build(); //?初始化數(shù)據(jù)庫 using?(var?scope?=?app.Services.CreateScope()) {await?scope.ServiceProvider.GetRequiredService<TodoDbContext>().Database.EnsureCreatedAsync(); } //?配置?HTTP?請求管道 if?(app.Environment.IsDevelopment()) {app.UseSwagger();app.UseSwaggerUI(c?=>?c.SwaggerEndpoint("/swagger/v1/swagger.json",?"MinimalTodoAPI?v1")); } app.Map("/health",?Results.Ok); app.MapGet("/contextSample",?(HttpContext?context)?=>{return?Results.Ok(context.Request.Query);}).ExcludeFromDescription();?//?從?swagger?中排除此?API//?Todo?的增刪改查?API app.MapGet("/api/todo",?(TodoDbContext?dbContext)?=>?dbContext.TodoItems.AsNoTracking().ToArrayAsync()); app.MapPost("/api/todo",?async?(TodoItem?item,?TodoDbContext?dbContext)?=>? {if(string.IsNullOrWhiteSpace(item?.Title)){return?Results.BadRequest();}item.Id?=?0;item.CreatedAt?=?DateTime.UtcNow;dbContext.TodoItems.Add(item);await?dbContext.SaveChangesAsync();return?Results.Created($"/api/todo/{item.Id}",?item); }); app.MapPut("/api/todo/{id}",?async?(int?id,?TodoItem?item,?TodoDbContext?dbContext)?=>? {if(id?<=?0?||?string.IsNullOrWhiteSpace(item?.Title)){return?Results.BadRequest();}var?todo?=?await?dbContext.TodoItems.FindAsync(id);if(todo?is?null){return?Results.NotFound();}todo.Title?=?item.Title;todo.Description?=?item.Description;todo.Done?=?item.Done;await?dbContext.SaveChangesAsync();return?Results.Ok(todo); });//?認(rèn)證授權(quán)? app.UseAuthentication(); app.UseAuthorization();app.MapDelete("/api/todo/{id}",?async?(int?id,?TodoDbContext?dbContext)?=> {if?(id?<=?0){return?Results.BadRequest();}var?todo?=?await?dbContext.TodoItems.FindAsync(id);if?(todo?is?null){return?Results.NotFound();}dbContext.Remove(todo);await?dbContext.SaveChangesAsync();return?Results.Ok(todo); }).RequireAuthorization();app.Run();上面示例注冊 EF Core DbContext 的時(shí)候用的上次我們介紹的簡化后的注冊方式?EF Core 6 簡化的數(shù)據(jù)庫上下文注冊
我們可以使用 MapGet/MapPost/MapPut/MapDelete 來限制請求方法,可以使用 Results 來方便的返回 API 結(jié)果, 類似于在 Controller 里調(diào)用 Ok/BadRequest/NotFound 等方法
swagger 界面:
swagger ui我們來測試一下需要認(rèn)證的 Delete API, 前面我們注冊服務(wù)的時(shí)候使用了一個(gè)自定義的一個(gè)基于 query string 的認(rèn)證方式以方便進(jìn)行測試,下面我們來測試一下,首先需要調(diào)用 POST ?API 來創(chuàng)建一個(gè) todo,然后調(diào)用 GET API 來確認(rèn)一下 todo 創(chuàng)建成功了,之后就可以測試我們的 DELETE API 了
我這里使用之前開發(fā)的 dotnet-httpie(dotnet-HTTPie) 來進(jìn)行測試,你也可以使用 Postman 或者別的工具來測試
首先執(zhí)行下面的命令
http?delete?-v?--schema=https?:7229/api/todo/1HTTP 請求響應(yīng)信息如下:
DELETE?/api/todo/1?HTTP/1.1 Host:?localhost:7229 Schema:?https User-Agent:?dotnet-HTTPie/0.1.1HTTP/1.1?401?Unauthorized Content-Length:?0 Date:?Sun,?19?Sep?2021?15:59:19?GMT Server:?Kestrel這里我們沒有提供任何的認(rèn)證相關(guān)的信息,所以 API 返回了 401
接著我們提供認(rèn)證信息來測試一下,在 query string 中添加 userId 和 userName 信息,執(zhí)行下面的命令
http?delete?-v?--schema=https?:7229/api/todo/1?userId==1?userName==testHTTP 請求響應(yīng)信息如下:
DELETE?/api/todo/1?userId=1&userName=test?HTTP/1.1 Host:?localhost:7229 Schema:?https User-Agent:?dotnet-HTTPie/0.1.1HTTP/1.1?200?OK Content-Type:?application/json;?charset=utf-8 Date:?Sun,?19?Sep?2021?16:04:29?GMT Server:?Kestrel Transfer-Encoding:?chunked{"id":1,"title":"test","description":"test","done":false,"createdAt":"2021-09-19T15:57:31.3370653"}可以看到此時(shí)返回了 200,已經(jīng)刪除成功了,不再是 401 了,我們也可以再調(diào)用一下?list?API 來看一下是否真的被刪除了,可以看到已經(jīng)沒有元素返回了
對于創(chuàng)建一個(gè)新 todo 的 POST API 也可以使用?dotnet-httpie 來方便的請求
More
對于簡單的快速試錯(cuò)的 API 推薦使用 Minimal API 來實(shí)現(xiàn),問題不大,但是比較復(fù)雜的應(yīng)用個(gè)人還是推薦走 MVC/Web API 的形式,更為成熟,功能更全面,Minimal API 很多功能不支持或者支持的不太好,比如說 Minimal API 是不支持對 model 進(jìn)行驗(yàn)證的,是沒有 ModelState 的,即使 model 里聲明了 Required 等驗(yàn)證,在 Minimal API 里也是不起作用的,也不支持 API-Version,另外對于 API 的分組支持也是比較弱的,要自己指定 tag 去分組,不如使用 Controller 簡單方便
上面的源碼可以在 Github 上獲取?https://github.com/WeihanLi/SamplesInPractice/tree/master/net6sample/MinimalTodoAPI
對于 Minimal API 的使用,微軟專門做了一個(gè)文檔網(wǎng)站來介紹其使用,可以參考:https://minimal-apis.github.io/
另外微軟的大佬 David 在 Gist 上也有一篇關(guān)于 Minimal API 的總結(jié),可以參考:https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727
References
https://github.com/WeihanLi/SamplesInPractice/tree/master/net6sample/MinimalTodoAPI
https://github.com/Minimal-APIs/minimal-apis.github.io
https://minimal-apis.github.io/
https://gist.github.com/davidfowl/ff1addd02d239d2d26f4648a06158727
ASP.NET Core 6 Minimal API
使用 Minimal API 改造動(dòng)態(tài)文件提供者
總結(jié)
以上是生活随笔為你收集整理的Minimal API Todo Sample的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 将.net framework 4 部署
- 下一篇: .NET 6 中的HTTP 3支持