網(wǎng)站首頁 編程語言 正文
在 ASP.NET Core 中處理 Web 應(yīng)用程序時(shí),我們可能經(jīng)常希望構(gòu)建輕量級(jí)服務(wù),也就是沒有模板或控制器類的服務(wù)。
輕量級(jí)服務(wù)可以降低資源消耗,而且能夠提高性能。我們可以在 Startup 或 Program 類中創(chuàng)建這些輕量級(jí)服務(wù)或 API。
1. 使用 VS2022 創(chuàng)建 ASP.NET Core 項(xiàng)目
我們?cè)?Visual Studio 2022 中創(chuàng)建一個(gè) ASP.NET Core 項(xiàng)目。按照以下步驟在 Visual Studio 2022 中創(chuàng)建一個(gè)新的 ASP.NET Core Web API 6 項(xiàng)目。
- 1) 啟動(dòng) Visual Studio 2022 IDE。
- 2) 單擊 “Create new project”。
- 3) 在 “Create new project” 窗口中,從顯示的模板列表中選擇 “ASP.NET Core Web API”。
- 4) 點(diǎn)擊下一步。
- 5) 在 “Configure your new project” 窗口中,指定新項(xiàng)目的名稱和位置。
- 6) 根據(jù)您的偏好,可選擇選中 “Place solution and project in the same directory” 復(fù)選框。
- 7) 點(diǎn)擊下一步。
- 8) 在接下來顯示的 “Additional Information” 窗口中,從頂部的下拉列表中選擇 .NET 6.0 作為目標(biāo)框架。將 “Authentication Type” 保留為 “None”(默認(rèn))。
- 9) 確保未選中 “Enable Docker,”、“Configure for HTTPS” 和 “Enable Open API Support” 復(fù)選框,因?yàn)槲覀儾粫?huì)在此處使用任何這些功能。您也可以選擇取消選中 “Use controllers(取消選中以使用最少的 API)” 復(fù)選框,因?yàn)槲覀儗?chuàng)建自己的控制器。
- 10) 單擊創(chuàng)建。
這將在 Visual Studio 2022 中創(chuàng)建一個(gè)新的 ASP.NET Core 6 Web API 項(xiàng)目。我們將在本文的后續(xù)部分中使用該項(xiàng)目,來說明如何使用輕量級(jí)服務(wù)。
2. 在 ASP.NET Core 中啟用一個(gè)輕量級(jí)的服務(wù)
由于我們將構(gòu)建不需要控制器的輕量級(jí)服務(wù),所以應(yīng)該刪除 Controllers solution 文件夾和默認(rèn)創(chuàng)建的任何模型類。
接下來,打開 Properties solution 文件夾下的 launchSettings.json 文件,刪除或注釋掉 launchUrl 鍵值對(duì),如下面給出的代碼所示。
其中,launchUrl 是指應(yīng)用程序的主機(jī)。當(dāng)應(yīng)用程序啟動(dòng)時(shí),launchURL 中指定的 URL 用于啟動(dòng)應(yīng)用程序。
如果 URL 錯(cuò)誤或不存在,應(yīng)用程序?qū)⒃趩?dòng)時(shí)拋出錯(cuò)誤。通過刪除 launchUrl 或?qū)⑵渥⑨尩簦覀兛梢源_保應(yīng)用程序不使用默認(rèn)的 launchUrl 來啟動(dòng)應(yīng)用程序,從而避免任何錯(cuò)誤。一旦 launchUrl 被刪除,應(yīng)用程序?qū)⒒氐?5000 端口。
"profiles": { "Light_Weight_Services": { "commandName": "Project", "dotnetRunMessages": true, "launchBrowser": true, //"launchUrl": "", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, //"launchUrl": "", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }
3. 在 ASP.NET Core 中使用 IEndpointConventionBuilder 擴(kuò)展方法
我們可以利用 IEndpointConventionBuilder 接口的一些擴(kuò)展方法來映射請(qǐng)求。
以下是這些擴(kuò)展方法的列表:
- MapGet
- MapPost
- MapDelete
- MapPut
- MapRazorPages
- MapControllers
- MapHub
- MapGrpcServices
MapGet、MapPost、MapDelete 和 MapPut 方法用于將請(qǐng)求委托連接到路由系統(tǒng)。MapRazorPages 用于 RazorPages,MapControllers 用于 Controllers,MapHub 用于 SignalR,MapGrpcService 用于 gRPC。
以下代碼說明了怎么使用 MapGet 創(chuàng)建 HTTP Get 端點(diǎn)。
endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); });
我們創(chuàng)建一個(gè)名為 Author 的 C# 文件,包含以下代碼:
public class Author { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
創(chuàng)建一個(gè) Author 的只讀列表,并填充一些數(shù)據(jù),如下所示:
private readonly List<Author> _authors; public Startup(IConfiguration configuration) { _authors = new List<Author> { new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal" }, new Author { Id = 2, FirstName = "Steve", LastName = "Smith" }, new Author { Id = 3, FirstName = "Julie", LastName = "Lerman" } }; Configuration = configuration; }
我們可以使用以下代碼創(chuàng)建另一個(gè)端點(diǎn),并以 JSON 格式返回作者列表。
endpoints.MapGet("/authors", async context => { var authors = _authors == null ? new List<Author>() : _authors; var response = JsonSerializer.Serialize(authors); await context.Response.WriteAsync(response); });
4. 在 ASP.NET Core 中使用輕量級(jí)服務(wù)檢索記錄
要根據(jù) Id 檢索特定記錄,我們可以編寫以下代碼:
endpoints.MapGet("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x=> x.Id == id); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); });
5. 在 ASP.NET Core 中使用輕量級(jí)服務(wù)創(chuàng)建記錄
要使用 HTTP Post 添加數(shù)據(jù),我們可以利用 MapPost 擴(kuò)展方法,如下所示:
endpoints.MapPost("/", async context => { var author = await context.Request.ReadFromJsonAsync<Author>(); _authors.Add(author); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); });
6. 在 ASP.NET Core 中使用輕量級(jí)服務(wù)刪除記錄
要?jiǎng)h除數(shù)據(jù),我們可以利用 MapDelete 擴(kuò)展方法,如下所示:
endpoints.MapDelete("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x => x.Id == id); _authors.Remove(author); var response = JsonSerializer.Serialize(_authors); await context.Response.WriteAsync(response); });
7. ASP.NET Core 中輕量級(jí)服務(wù)的配置方法
下面是 Startup 類的 Configure 方法的完整源碼:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); }); endpoints.MapGet("/authors", async context => { var authors = _authors == null ? new List<Author>() : _authors; var response = JsonSerializer.Serialize(authors); await context.Response.WriteAsync(response); }); endpoints.MapGet("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x=> x.Id == id); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); }); endpoints.MapPost("/", async context => { var author = await context.Request.ReadFromJsonAsync<Author>(); _authors.Add(author); var response = JsonSerializer.Serialize(author); await context.Response.WriteAsync(response); }); endpoints.MapDelete("/authors/{id:int}", async context => { var id = int.Parse((string)context.Request.RouteValues["id"]); var author = _authors.Find(x => x.Id == id); _authors.Remove(author); var response = JsonSerializer.Serialize(_authors); await context.Response.WriteAsync(response); }); }); }
8. 在 ASP.NET Core 的 Program 類中創(chuàng)建輕量級(jí)服務(wù)
在 ASP.NET 6 中還有另一種創(chuàng)建輕量級(jí)服務(wù)的方法。我們創(chuàng)建新的 ASP.NET Core 6 空項(xiàng)目時(shí),默認(rèn)情況下不會(huì)創(chuàng)建 Startup.cs 文件。因此,我們可以在 Program.cs 文件中編寫代碼,創(chuàng)建輕量級(jí)服務(wù)。
下面的例子說明如何執(zhí)行此操作:
app.MapGet("/", () => "Hello World!"); app.MapDelete("/{id}", (Func<int, bool>)((id) => { // 刪除記錄代碼 return true; })); app.MapPost("/", (Func<Author, bool>)((author) => { // 添加記錄代碼 return true; })); app.Run();
輕量級(jí)服務(wù)或 API 沒有模板,也不需要控制器類來創(chuàng)建它們。
我們可以在 Startup 或 Program 類中創(chuàng)建此類服務(wù)。
如果我們要在輕量級(jí)服務(wù)中實(shí)現(xiàn)授權(quán),可以利用 IEndpointConventionBuilder 接口的 RequireAuthorization 擴(kuò)展方法。
參考資料:
?編程寶庫???
原文鏈接:https://www.cnblogs.com/wanghao72214/p/15659718.html
相關(guān)推薦
- 2022-07-30 Go語言sort包函數(shù)使用示例_Golang
- 2022-11-06 詳解Python中的null是什么_python
- 2022-08-22 C++動(dòng)態(tài)規(guī)劃算法實(shí)現(xiàn)矩陣鏈乘法_C 語言
- 2022-04-12 Docker容器部署consul的詳細(xì)步驟_docker
- 2023-07-24 uniapp開發(fā)小程序,包過大解決方案
- 2022-08-28 go?zero微服務(wù)高在請(qǐng)求量下如何優(yōu)化_Golang
- 2022-12-15 詳解C#中HttpClient的用法及相關(guān)問題的解決方法_C#教程
- 2022-06-25 pytorch中permute()函數(shù)用法補(bǔ)充說明(矩陣維度變化過程)_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支