天天看點

【翻譯】在Visual Studio中使用Asp.Net Core MVC建立你的第一個Web API應用(一)概況建立項目添加一個模型類添加Repository類注入這個Repository添加控制器擷取to-do項路由和URL路徑傳回值原文連結

HTTP is not just for serving up web pages. It’s also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop apps.

現在的HTTP協定不再隻是為浏覽網頁而服務,還能建構一個強大的APIs平台提供資料服務。HTTP是簡單的、靈活的、無處不在的。幾乎你所知的所有平台都有自己的HTTP庫,是以HTTP服務擁有衆多使用者,包括浏覽器、移動裝置和傳統的桌面應用等。

In this tutorial, you’ll build a simple web API for managing a list of "to-do" items. You won’t build any UI in this tutorial.

在本教程中,你将建造一個簡單的web api去管理“to-do”項目,在整個過程中不需要建構UI。

ASP.NET Core has built-in support for MVC building Web APIs. Unifying the two frameworks makes it simpler to build apps that include both UI (HTML) and APIs, because now they share the same code base and pipeline.

Asp.Net Core已經内置了使用MVC建立Web APIs。統一了兩個架構可以更輕松的建立應用,包括UI(Html)和APIs,因為現在它們共用了相同的基類和管道。

Here is the API that you’ll create:

以下是所需要建立的API:

【翻譯】在Visual Studio中使用Asp.Net Core MVC建立你的第一個Web API應用(一)概況建立項目添加一個模型類添加Repository類注入這個Repository添加控制器擷取to-do項路由和URL路徑傳回值原文連結

The following diagram shows the basic design of the app.

以下是這個應用的基礎設計圖解:

【翻譯】在Visual Studio中使用Asp.Net Core MVC建立你的第一個Web API應用(一)概況建立項目添加一個模型類添加Repository類注入這個Repository添加控制器擷取to-do項路由和URL路徑傳回值原文連結

在這裡我們将用Postman來測試應用,其他任何支援web api(浏覽器,移動應用等等)在這裡不再講述。

A model is an object that represents the data in your application. In this case, the only model is a to-do item. Models are represented as simple C# classes (POCOs).

在這個應用中一個模型代表一個對象,在這個範例裡,僅僅隻有TO-DO item模型。這個模型就是簡單的C#類

A controller is an object that handles HTTP requests and creates the HTTP response. This app will have a single controller.

控制器就是控制HTTP請求和傳回的對象,這個應用隻有簡單的控制器。

Start Visual Studio. From the File menu, select New > Project.

打開Visual Studio,從File目錄中,選擇New > Project。

Select the ASP.NET Core Web Application (.NET Core) project template. Name the project <code>TodoApi</code>, clear Host in the cloud, and tap OK.

選擇ASP.NET Core Web Application (.NET Core) 項目模闆,名字為:TodoApi,不勾選Host in the cloud,點選OK。

【翻譯】在Visual Studio中使用Asp.Net Core MVC建立你的第一個Web API應用(一)概況建立項目添加一個模型類添加Repository類注入這個Repository添加控制器擷取to-do項路由和URL路徑傳回值原文連結

In the New ASP.NET Core Web Application (.NET Core) - TodoApi dialog, select the Web API template. Tap OK.

在New ASP.NET Core Web Application (.NET Core) - TodoApi對話框中,選擇Web Api模闆,點選OK。

【翻譯】在Visual Studio中使用Asp.Net Core MVC建立你的第一個Web API應用(一)概況建立項目添加一個模型類添加Repository類注入這個Repository添加控制器擷取to-do項路由和URL路徑傳回值原文連結

Add a folder named "Models". In Solution Explorer, right-click the project. Select Add &gt; New Folder. Name the folder Models.

在解決方案目錄中,添加一個名為“Models”檔案夾,右鍵項目-選擇Add &gt; New Folder,取名:Models。

Add a <code>TodoItem</code> class. Right-click the Models folder and select Add &gt; Class. Name the class <code>TodoItem</code> and tap Add.

添加TodoItem類,右鍵Models目錄,選擇Add &gt; Class ,取名:TodoItem,點選添加。

Replace the generated code with:

把以下代碼替換自動生成的代碼:

A repository is an object that encapsulates the data layer. The repository contains logic for retrieving and mapping data to an entity model. Even though the example app doesn’t use a database, it’s useful to see how you can inject a repository into your controllers. Create the repository code in the Models folder.

Repository是一個封裝了資料通路的對象。這個Repository包含了檢索邏輯和資料映射到實體對象的功能。雖然在這個範例中我們不使用資料庫,但你能看到在你的controller中注入repository,在Models檔案夾中建立Repository代碼。

Defining a repository interface named <code>ITodoRepository</code>. Use the class template (Add New Item &gt; Class)

定義一個名為:ITodoRepository的repository接口,使用類模闆(Add New Item &gt; Class)

This interface defines basic CRUD operations.

這個接口定義了基本的CRUD操作。

Add a <code>TodoRepository</code> class that implements <code>ITodoRepository</code>:

添加一個TodoRepository類繼承自ITodoRepository接口:

Build the app to verify you don't have any compiler errors.

生成這個應用,檢查下是否有編譯錯誤。

因為定義了一個repository接口,我們能夠使repository類和MVC控制器能夠分離使用。我們不需要在controller中執行個體化一個TodoRepository類,隻需要使用ASP.NET Core内置的依賴注入即可。

This approach makes it easier to unit test your controllers. Unit tests should inject a mock or stub version of <code>ITodoRepository</code>. That way, the test narrowly targets the controller logic and not the data access layer.

這種方式能夠讓你更簡單的對你的控制器進行單元測試。在單元測試中隻需要注入一個mock的ITodoRepository。這樣我們測試的時候就不需要通路資料層就能測試目标控制器的邏輯代碼。

In order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs file. Add the following using directive:

我們需要注冊一個DI容器以友善我們的repository注入到這個控制器中。打開Startup.cs檔案,添加引用代碼:

In the <code>ConfigureServices</code> method, add the highlighted code:

在ConfigureServices方法中,添加以下高亮代碼:

In Solution Explorer, right-click the Controllers folder. Select Add &gt; New Item. In the Add New Item dialog, select the Web API Controller Class template. Name the class <code>TodoController</code>.

在解決方案面闆中,右鍵Controllers目錄,選擇Add &gt; New Item。在添加對話框中,選擇Web Api Controller Class模闆,取名:TodoController。

Replace the generated code with the following:

替換以下代碼:

This defines an empty controller class. In the next sections, we'll add methods to implement the API.

這裡定義了一個空的控制類,下一步我們會添加API相關方法。

To get to-do items, add the following methods to the <code>TodoController</code> class.

在TodoController類中添加以下方法擷取一個to-do項:

These methods implement the two GET methods:

這些方法包含了以下兩個方法:

<code>GET /api/todo</code>

<code>GET /api/todo/{id}</code>

Here is an example HTTP response for the <code>GetAll</code> method:

下面是使用GetAll方法所傳回的内容:

在範例後面,我将示範如何使用Postman檢視HTTP response。

The <code>[HttpGet]</code> attribute (<code>HttpGetAttribute</code>) specifies an HTTP GET method. The URL path for each method is constructed as follows:

HttpGet特性提供了一個HTTP Get方法。這個方法構造了如下的URL路徑:

Take the template string in the controller’s route attribute, <code>[Route("api/[controller]")]</code>

<code>在控制器的路由特性中檢視模闆字元串,<code>[Route("api/[controller]")]</code></code>

替換Controller名,類必須以Controller結尾。這個範例裡我們使用TodoController作為類名,Asp.Net Core路由是不區分大小寫的。

If the <code>[HttpGet]</code> attribute has a template string, append that to the path. This sample doesn't use a template string.

如果這個HttpGet特性含有模闆字元的話,添加相應路徑,我們不使用預設字元。

In the <code>GetById</code> method:

在這個GetById方法中:

<code>"{id}"</code> is a placeholder variable for the ID of the <code>todo</code> item. When <code>GetById</code> is invoked, it assigns the value of "{id}" in the URL to the method's <code>id</code> parameter.

{id}是todo項ID的占位符,當GetById調用時,URL相應的{id}值會賦予方法中id參數。

GetAll方法傳回了一個IEnumerable。MVC會自動的把這個對象序列化成JSON格式并把格式化後的内容寫入到響應消息的body中。如果沒有一場,這個響應傳回代碼為200。(如果有為止錯誤将傳回5xx錯誤資訊)。

In contrast, the <code>GetById</code> method returns the more general <code>IActionResult</code> type, which represents a wide range of return types. <code>GetById</code> has two different return types:

相比之下,GetById方法傳回了一個IActionResult類型,這樣能傳回更多不同的傳回類型。GetById有2個不同的傳回類型:

If no item matches the requested ID, the method returns a 404 error. This is done by returning <code>NotFound</code>.

如果沒有比對到響應的item,這個方法傳回404錯誤,傳回NotFound。

Otherwise, the method returns 200 with a JSON response body. This is done by returning an <code>ObjectResult</code>

<code>相反,這個方法傳回200代碼并響應一個JSON對象,類型為:ObjectResult。</code>

<a href="https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api">https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api</a>