【翻译】在Visual Studio中使用Asp.Net Core MVC创建你的第一个Web API应用(一)

简介: 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 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:

image

The following diagram shows the basic design of the app.

以下是这个应用的基础设计图解:

img_3404d72f29d7a5979a6d0c9171d3f195.png

  • The client is whatever consumes the web API (browser, mobile app, and so forth). We aren’t writing a client in this tutorial. We'll use Postman to test the app.

  • 在这里我们将用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请求和返回的对象,这个应用只有简单的控制器。

  • To keep the tutorial simple, the app doesn’t use a database. Instead, it just keeps to-do items in memory. But we’ll still include a (trivial) data access layer, to illustrate the separation between the web API and the data layer. For a tutorial that uses a database, see Building your first ASP.NET Core MVC app with Visual Studio.

  • 为了保持简单范例,这个应用不使用数据库,我们仅需要把对象保存在内存中。但是我们还是应该保持创建一个数据访问层,这样能更好的表示web API和数据层之间的分离。如果需要使用数据库,可以参考:Building your first ASP.NET Core MVC app with Visual Studio

创建项目

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 TodoApi, clear Host in the cloud, and tap OK.

选择ASP.NET Core Web Application (.NET Core) 项目模板,名字为:TodoApi,不勾选Host in the cloud,点击OK。

img_e727b620af0f4820be71d960c54bdffb.png

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。

img_ba0e30eee694a0b6ad86369d74e3abb2.png

添加一个模型类

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

在解决方案目录中,添加一个名为“Models”文件夹,右键项目-选择Add > New Folder,取名:Models。

add-folder.png

Add a TodoItem class. Right-click the Models folder and select Add > Class. Name the class TodoItem and tap Add.

添加TodoItem类,右键Models目录,选择Add > Class ,取名:TodoItem,点击添加。

Replace the generated code with:

把以下代码替换自动生成的代码:

namespace TodoApi.Models
{
    public class TodoItem
    {
        public string Key { get; set; }
        public string Name { get; set; }
        public bool IsComplete { get; set; }
    }
}

添加Repository类

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 ITodoRepository. Use the class template (Add New Item > Class)

定义一个名为:ITodoRepository的repository接口,使用类模板(Add New Item > Class)

using System.Collections.Generic;

namespace TodoApi.Models
{
    public interface ITodoRepository
    {
        void Add(TodoItem item);
        IEnumerable<TodoItem> GetAll();
        TodoItem Find(string key);
        TodoItem Remove(string key);
        void Update(TodoItem item);
    }
}

This interface defines basic CRUD operations.

这个接口定义了基本的CRUD操作。

Add a TodoRepository class that implements ITodoRepository:

添加一个TodoRepository类继承自ITodoRepository接口:

using System;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace TodoApi.Models
{
    public class TodoRepository : ITodoRepository
    {
        private static ConcurrentDictionary<string, TodoItem> _todos =
              new ConcurrentDictionary<string, TodoItem>();

        public TodoRepository()
        {
            Add(new TodoItem { Name = "Item1" });
        }

        public IEnumerable<TodoItem> GetAll()
        {
            return _todos.Values;
        }

        public void Add(TodoItem item)
        {
            item.Key = Guid.NewGuid().ToString();
            _todos[item.Key] = item;
        }

        public TodoItem Find(string key)
        {
            TodoItem item;
            _todos.TryGetValue(key, out item);
            return item;
        }

        public TodoItem Remove(string key)
        {
            TodoItem item;
            _todos.TryRemove(key, out item);
            return item;
        }

        public void Update(TodoItem item)
        {
            _todos[item.Key] = item;
        }
    }
}

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

生成这个应用,检查下是否有编译错误。

注入这个Repository

By defining a repository interface, we can decouple the repository class from the MVC controller that uses it. Instead of instantiating a TodoRepository inside the controller we will inject an ITodoRepository using the built-in support in ASP.NET Core for dependency injection.

因为定义了一个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 ITodoRepository. 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文件,添加引用代码:

using TodoApi.Models;

In the ConfigureServices method, add the highlighted code:

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

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    
}

添加控制器

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

在解决方案面板中,右键Controllers目录,选择Add > New Item。在添加对话框中,选择Web Api Controller Class模板,取名:TodoController。

Replace the generated code with the following:

替换以下代码:

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;

namespace TodoApi.Controllers
{
    [Route("api/[controller]")]
    public class TodoController : Controller
    {
        public TodoController(ITodoRepository todoItems)
        {
            TodoItems = todoItems;
        }
        public ITodoRepository TodoItems { get; set; }
    }
}

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

这里定义了一个空的控制类,下一步我们会添加API相关方法。

获取to-do项

To get to-do items, add the following methods to the TodoController class.

在TodoController类中添加以下方法获取一个to-do项:

[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
    return TodoItems.GetAll();
}

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)
{
    var item = TodoItems.Find(id);
    if (item == null)
    {
        return NotFound();
    }
    return new ObjectResult(item);
}

These methods implement the two GET methods:

这些方法包含了以下两个方法:

  • GET /api/todo

  • GET /api/todo/{id}

Here is an example HTTP response for the GetAll method:

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

HTTP/1.1 200 OK
   Content-Type: application/json; charset=utf-8
   Server: Microsoft-IIS/10.0
   Date: Thu, 18 Jun 2015 20:51:10 GMT
   Content-Length: 82

   [{"Key":"4f67d7c5-a2a9-4aae-b030-16003dd829ae","Name":"Item1","IsComplete":false}]

Later in the tutorial I'll show how you can view the HTTP response using Postman.

在范例后面,我将演示如何使用Postman查看HTTP response。

路由和URL路径

The [HttpGet] attribute (HttpGetAttribute) 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, [Route("api/[controller]")]
  • 在控制器的路由特性中查看模板字符串,[Route("api/[controller]")]
  • Replace "[Controller]" with the name of the controller, which is the controller class name minus the "Controller" suffix. For this sample, the controller class name is TodoController and the root name is "todo". ASP.NET Core routing is not case sensitive.
  • 替换Controller名,类必须以Controller结尾。这个范例里我们使用TodoController作为类名,Asp.Net Core路由是不区分大小写的。
  • If the [HttpGet] attribute has a template string, append that to the path. This sample doesn't use a template string.
  • 如果这个HttpGet特性含有模板字符的话,添加相应路径,我们不使用默认字符。

In the GetById method:

在这个GetById方法中:

[HttpGet("{id}", Name = "GetTodo")]
public IActionResult GetById(string id)

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

{id}是todo项ID的占位符,当GetById调用时,URL相应的{id}值会赋予方法中id参数。

Name = "GetTodo" creates a named route and allows you to link to this route in an HTTP Response. I'll explain it with an example later. See Routing to Controller Actions for detailed information.

[Name="GetTodo" ]创建了一个名为GetTodo的路由名,它允许在HTTP响应中链接到你的路由上。稍后会做演示,详见:Routing to Controller Actions

返回值

The GetAll method returns an IEnumerable. MVC automatically serializes the object to JSON and writes the JSON into the body of the response message. The response code for this method is 200, assuming there are no unhandled exceptions. (Unhandled exceptions are translated into 5xx errors.)

GetAll方法返回了一个IEnumerable。MVC会自动的把这个对象序列化成JSON格式并把格式化后的内容写入到响应消息的body中。如果没有一场,这个响应返回代码为200。(如果有为止错误将返回5xx错误信息)。

In contrast, the GetById method returns the more general IActionResult type, which represents a wide range of return types. GetById 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 NotFound.

  • 如果没有匹配到响应的item,这个方法返回404错误,返回NotFound。

  • Otherwise, the method returns 200 with a JSON response body. This is done by returning an ObjectResult

  • 相反,这个方法返回200代码并响应一个JSON对象,类型为:ObjectResult。

原文链接

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api

相关文章
|
6天前
|
开发框架 监控 前端开发
在 ASP.NET Core Web API 中使用操作筛选器统一处理通用操作
【9月更文挑战第27天】操作筛选器是ASP.NET Core MVC和Web API中的一种过滤器,可在操作方法执行前后运行代码,适用于日志记录、性能监控和验证等场景。通过实现`IActionFilter`接口的`OnActionExecuting`和`OnActionExecuted`方法,可以统一处理日志、验证及异常。创建并注册自定义筛选器类,能提升代码的可维护性和复用性。
|
6天前
|
开发框架 .NET 中间件
ASP.NET Core Web 开发浅谈
本文介绍ASP.NET Core,一个轻量级、开源的跨平台框架,专为构建高性能Web应用设计。通过简单步骤,你将学会创建首个Web应用。文章还深入探讨了路由配置、依赖注入及安全性配置等常见问题,并提供了实用示例代码以助于理解与避免错误,帮助开发者更好地掌握ASP.NET Core的核心概念。
18 3
|
11天前
|
开发框架 前端开发 .NET
VB.NET中如何利用ASP.NET进行Web开发
在VB.NET中利用ASP.NET进行Web开发是一个常见的做法,特别是在需要构建动态、交互式Web应用程序时。ASP.NET是一个由微软开发的开源Web应用程序框架,它允许开发者使用多种编程语言(包括VB.NET)来创建Web应用程序。
39 5
|
28天前
|
开发框架 NoSQL .NET
利用分布式锁在ASP.NET Core中实现防抖
【9月更文挑战第5天】在 ASP.NET Core 中,可通过分布式锁实现防抖功能,仅处理连续相同请求中的首个请求,其余请求返回 204 No Content,直至锁释放。具体步骤包括:安装分布式锁库如 `StackExchange.Redis`;创建分布式锁服务接口及其实现;构建防抖中间件;并在 `Startup.cs` 中注册相关服务和中间件。这一机制有效避免了短时间内重复操作的问题。
|
2月前
|
UED 存储 自然语言处理
【语言无界·体验无疆】解锁Vaadin应用全球化秘籍:从代码到文化,让你的应用畅游世界每一个角落!
【8月更文挑战第31天】《国际化与本地化实战:构建多语言支持的Vaadin应用》详细介绍了如何使用Vaadin框架实现应用的国际化和本地化,提升用户体验和市场竞争力。文章涵盖资源文件的创建与管理、消息绑定与动态加载、日期和数字格式化及文化敏感性处理等方面,通过具体示例代码和最佳实践,帮助开发者构建适应不同语言和地区设置的Vaadin应用。通过这些步骤,您的应用将更加灵活,满足全球用户需求。
35 0
|
2月前
|
API 数据库 UED
全面解析构建高性能API的秘诀:运用Entity Framework Core与异步编程提升Web应用响应速度及并发处理能力的详细指南与实践案例
【8月更文挑战第31天】本文详细介绍了如何利用 Entity Framework Core (EF Core)的异步编程特性构建高性能 API。通过创建基于 EF Core 的 .NET Core Web API 项目,配置数据库上下文,并定义领域模型,文章展示了如何使用异步方法进行数据查询、加载相关实体及事务处理。具体代码示例涵盖了 GET、POST、PUT 和 DELETE 操作,全面展示了 EF Core 异步编程的优势,有助于提升 API 的响应速度和处理能力。
34 0
|
2月前
|
开发框架 监控 .NET
开发者的革新利器:ASP.NET Core实战指南,构建未来Web应用的高效之道
【8月更文挑战第28天】本文探讨了如何利用ASP.NET Core构建高效、可扩展的Web应用。ASP.NET Core是一个开源、跨平台的框架,具有依赖注入、配置管理等特性。文章详细介绍了项目结构规划、依赖注入配置、中间件使用及性能优化方法,并讨论了安全性、可扩展性以及容器化的重要性。通过这些技术要点,开发者能够快速构建出符合现代Web应用需求的应用程序。
35 0
|
2月前
|
开发框架 监控 .NET
【Azure 应用程序见解】在Docker中运行的ASP.NET Core应用如何开启Application Insights的Profiler Trace呢?
【Azure 应用程序见解】在Docker中运行的ASP.NET Core应用如何开启Application Insights的Profiler Trace呢?
|
2月前
|
Linux C# C++
【Azure App Service For Container】创建ASP.NET Core Blazor项目并打包为Linux镜像发布到Azure应用服务
【Azure App Service For Container】创建ASP.NET Core Blazor项目并打包为Linux镜像发布到Azure应用服务
|
前端开发 API JavaScript
关于MVC API参数传递问题
    1.单个参数: 需要加入限定条件[FromBody], 然后这样紧紧不够,特别需要注意的是前端js调用时并不是采用键值对的方式,而已值的形式,     2.
1108 0
下一篇
无影云桌面