<input id="ohw05"></input>
  • <table id="ohw05"><menu id="ohw05"></menu></table>
  • <var id="ohw05"></var>
  • <code id="ohw05"><cite id="ohw05"></cite></code>
    <label id="ohw05"></label>
    <var id="ohw05"></var>
  • 【翻譯】在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 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.

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

    • 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。

    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。

    添加一個模型類

    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 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();
    
        services.AddSingleton<ITodoRepository, TodoRepository>();
    }

    添加控制器

    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

    posted @ 2017-01-16 10:32  James.Ying  閱讀(614)  評論(0編輯  收藏  舉報
    国产美女a做受大片观看