天天看点

【翻译】在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>