使用VS2022在ASP.NET?Core中構(gòu)建輕量級服務(wù)
在 ASP.NET Core 中處理 Web 應(yīng)用程序時,我們可能經(jīng)常希望構(gòu)建輕量級服務(wù),也就是沒有模板或控制器類的服務(wù)。
輕量級服務(wù)可以降低資源消耗,而且能夠提高性能。我們可以在 Startup 或 Program 類中創(chuàng)建這些輕量級服務(wù)或 API。
1. 使用 VS2022 創(chuàng)建 ASP.NET Core 項目
我們在 Visual Studio 2022 中創(chuàng)建一個 ASP.NET Core 項目。按照以下步驟在 Visual Studio 2022 中創(chuàng)建一個新的 ASP.NET Core Web API 6 項目。
- 1) 啟動 Visual Studio 2022 IDE。
- 2) 單擊 “Create new project”。
- 3) 在 “Create new project” 窗口中,從顯示的模板列表中選擇 “ASP.NET Core Web API”。
- 4) 點擊下一步。
- 5) 在 “Configure your new project” 窗口中,指定新項目的名稱和位置。
- 6) 根據(jù)您的偏好,可選擇選中 “Place solution and project in the same directory” 復(fù)選框。
- 7) 點擊下一步。
- 8) 在接下來顯示的 “Additional Information” 窗口中,從頂部的下拉列表中選擇 .NET 6.0 作為目標框架。將 “Authentication Type” 保留為 “None”(默認)。
- 9) 確保未選中 “Enable Docker,”、“Configure for HTTPS” 和 “Enable Open API Support” 復(fù)選框,因為我們不會在此處使用任何這些功能。您也可以選擇取消選中 “Use controllers(取消選中以使用最少的 API)” 復(fù)選框,因為我們將創(chuàng)建自己的控制器。
- 10) 單擊創(chuàng)建。
這將在 Visual Studio 2022 中創(chuàng)建一個新的 ASP.NET Core 6 Web API 項目。我們將在本文的后續(xù)部分中使用該項目,來說明如何使用輕量級服務(wù)。
2. 在 ASP.NET Core 中啟用一個輕量級的服務(wù)
由于我們將構(gòu)建不需要控制器的輕量級服務(wù),所以應(yīng)該刪除 Controllers solution 文件夾和默認創(chuàng)建的任何模型類。
接下來,打開 Properties solution 文件夾下的 launchSettings.json 文件,刪除或注釋掉 launchUrl 鍵值對,如下面給出的代碼所示。
其中,launchUrl 是指應(yīng)用程序的主機。當應(yīng)用程序啟動時,launchURL 中指定的 URL 用于啟動應(yīng)用程序。
如果 URL 錯誤或不存在,應(yīng)用程序?qū)⒃趩訒r拋出錯誤。通過刪除 launchUrl 或?qū)⑵渥⑨尩?,我們可以確保應(yīng)用程序不使用默認的 launchUrl 來啟動應(yīng)用程序,從而避免任何錯誤。一旦 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 擴展方法
我們可以利用 IEndpointConventionBuilder 接口的一些擴展方法來映射請求。
以下是這些擴展方法的列表:
- MapGet
- MapPost
- MapDelete
- MapPut
- MapRazorPages
- MapControllers
- MapHub
- MapGrpcServices
MapGet、MapPost、MapDelete 和 MapPut 方法用于將請求委托連接到路由系統(tǒng)。MapRazorPages 用于 RazorPages,MapControllers 用于 Controllers,MapHub 用于 SignalR,MapGrpcService 用于 gRPC。
以下代碼說明了怎么使用 MapGet 創(chuàng)建 HTTP Get 端點。
endpoints.MapGet("/", async context => { await context.Response.WriteAsync("Hello World!"); });
我們創(chuàng)建一個名為 Author 的 C# 文件,包含以下代碼:
public class Author { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } }
創(chuàng)建一個 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)建另一個端點,并以 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 中使用輕量級服務(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 中使用輕量級服務(wù)創(chuàng)建記錄
要使用 HTTP Post 添加數(shù)據(jù),我們可以利用 MapPost 擴展方法,如下所示:
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 中使用輕量級服務(wù)刪除記錄
要刪除數(shù)據(jù),我們可以利用 MapDelete 擴展方法,如下所示:
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 中輕量級服務(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)建輕量級服務(wù)
在 ASP.NET 6 中還有另一種創(chuàng)建輕量級服務(wù)的方法。我們創(chuàng)建新的 ASP.NET Core 6 空項目時,默認情況下不會創(chuàng)建 Startup.cs 文件。因此,我們可以在 Program.cs 文件中編寫代碼,創(chuàng)建輕量級服務(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();
輕量級服務(wù)或 API 沒有模板,也不需要控制器類來創(chuàng)建它們。
我們可以在 Startup 或 Program 類中創(chuàng)建此類服務(wù)。
如果我們要在輕量級服務(wù)中實現(xiàn)授權(quán),可以利用 IEndpointConventionBuilder 接口的 RequireAuthorization 擴展方法。
參考資料:
?編程寶庫???
以上所述是小編給大家介紹的使用VS2022在ASP.NET Core中構(gòu)建輕量級服務(wù),希望對大家有所幫助。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
.NET微服務(wù)架構(gòu)CI/CD自動構(gòu)建Jenkins+Gitee
這篇文章介紹了.NET使用微服務(wù)架構(gòu)CI/CD自動構(gòu)建Jenkins+Gitee的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-01-01.NET實現(xiàn)可交互的WINDOWS服務(wù)的實例代碼
那么來看一下如何才能實現(xiàn)一個可交互的服務(wù)呢。步驟與實現(xiàn)基本的服務(wù)一樣2013-03-03.net core如何在網(wǎng)絡(luò)高并發(fā)下提高JSON的處理效率詳解
這篇文章主要給大家介紹了關(guān)于.net core如何在網(wǎng)絡(luò)高并發(fā)下提高JSON的處理效率的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學習或者使用.net core具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧2019-04-04asp.net中3種驗證碼示例(實現(xiàn)代碼)(數(shù)字,數(shù)字字母混和,漢字)
asp.net中3種驗證碼示例代碼,分別是數(shù)字,數(shù)字字母混和,漢字,需要的朋友可以參考下2012-10-10ASP.NET URL偽靜態(tài)重寫實現(xiàn)方法
ASP.NET下為靜態(tài)的實現(xiàn)方法。2009-12-12