ASP. NET Core Chinese Document Chapter 2 Guide (2) Use Visual Studio, ASP. NET, corestudio
Reference page:
Http://www.yuanjiaocheng.net/ASPNET-CORE/project-layout.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/projectjson.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-configuration.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-middleware.html
Http://www.yuanjiaocheng.net/ASPNET-CORE/core-exception.html
Original article: Building Your First Web API with ASP. NET Core MVC and Visual Studio
Prepared by Mike Wasson and Rick Anderson
Translation: Thank you (kiler)
Proofreaders: He Zhen, Liu Yi (AlexLEWIS), and Houzhi
HTTP not only provides Web Services. It is also a powerful platform for building public services and data APIs. HTTP protocol is simple, flexible, and ubiquitous. Almost any platform you can think of has HTTP support, so the HTTP service can be sent to a variety of clients, including browsers, mobile devices and traditional desktop applications.
In this tutorial, you will create a simple Web API to manage a "to-do" list. In this tutorial, you do not need to write any UI code.
ASP. NET Core has built-in support for building Web APIs with MVC Architecture. The two frameworks are unified to make it easy to build applications, including user interfaces (HTML) and APIs, because they now share the same code library and pipeline.
Note:
If you want to migrate an old Web API application to ASP. NET Core, refer to migrate from ASP. NET Web API
Overview
Here is the API you want to create:
API |
Description |
Request body |
Response body |
GET/api/todo |
Get all to-do items |
None |
Array of to-do items |
GET/api/todo/{id} |
Get item by ID |
None |
To-do item |
POST/api/todo |
Add a new item |
To-do item |
To-do item |
PUT/api/todo/{id} |
Update an existing item |
To-do item |
None |
DELETE/api/todo/{id} |
Deletes a specified item. |
None |
None |
The following chart shows the basic design of the application:
- No matter which client calls the API (browser, mobile app, etc ). We will not compile the client in this tutorial.
- ModelIs a class that represents your application data. In this case, there is only one model to-do item. The model is represented as a simple C # type (POCOs ),
- ControllerIs an object that processes an HTTP request and returns an HTTP response. In this example, only one controller is available.
- To ensure the simplicity of the tutorial, we do not use databases. As an alternative, we store the to-do item into the memory. However, we still include a data access layer (not important) to isolate the Web API and data layer. To use a database, see create an ASP. NET Core MVC application with Visual Studio.
Install Fiddler
We do not create a client. We use Fiddler to test the API. Fiddler is a Web debugging tool that allows you to send HTTP requests and view the original HTTP response.
Create a project
Start Visual Studio. SlaveFileMenu, selectNew>Project.
SelectASP. NET Core Web ApplicationProject template. Project name:TodoApi
And clickOK.
InNew ASP. NET Core Web Application (. NET Core)-TodoApiIn the dialog box, selectWeb APITemplate. ClickOK.
Add model class
The model indicates the data objects in the application. In this example, the only model used is a to-do item.
Add a directory named "Models. In the solution browser, right-click the project. SelectAdd>New Folder. Name the DirectoryModels.
Note:
You can place the model class anywhere in the project,ModelsIs the agreed default directory.
Next, addTodoItem
Class. Right-clickModelsDirectory and selectAdd>New Item.
InAdd New ItemIn the dialog box, selectClassTemplate. Name the classTodoItem
And clickOK.
Replace the generated code:
namespace TodoApi.Models{ public class TodoItem { public string Key { get; set; } public string Name { get; set; } public bool IsComplete { get; set; } }}
Add a storage class
RepositoryA class is a class that encapsulates the data layer and contains the business logic for retrieving data and ing it to the entity model class. Although the database is not used in this example, it is worth thinking about how Repository is injected into our Controller. InModelsDirectory to create the repository code.
DefineITodoRepository
Through the class template (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); }}
Interface defines basic CRUD operations.
Next, add a TodoRepository class that implements the ITodoRepository interface:
using System;using System.Collections.Generic;using System.Collections.Concurrent;namespace TodoApi.Models{ public class TodoRepository : ITodoRepository { 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.TryGetValue(key, out item); _todos.TryRemove(key, out item); return item; } public void Update(TodoItem item) { _todos[item.Key] = item; } }}
Generate the application to ensure there are no compilation errors.
Register warehouse
Defines the repository interface. We can decouple the storage class from the MVC Controller using it, instead of directly instantiating it in the Controller.TodoRepository
, We will use ASP. NET Core built-in function InjectionITodoRepository
For more information, see Dependency injection.
This method makes it easier to perform unit tests on your Controller. A Mock or stub ITodoRepository should be injected into the unit test. In this way, the test scope can be restricted to the business logic layer rather than the data access layer.
To inject repository into the controller, We must register the DI container. OpenStartup. csFile. Add the following command:
using TodoApi.Models;
InConfigureServices
Method to add the highlighted method:
Public void ConfigureServices (IServiceCollection services) {// Add framework services. services. addMvc (); // Add our repository type, highlighted services. addSingleton <ITodoRepository, TodoRepository> ();}
Add Controller
In the solution browser, right-clickControllersDirectory. SelectAdd>New Item. InAdd New ItemIn the dialog box, selectWeb API Controller ClassTemplate. Name itTodoController
.
Replace the generated code with the following code:
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; } }}
An empty controller class is defined here. In the next section, we will add code to implement the API.
Get to-do list
To obtain the to-do entry, add the following methodTodoController
Class.
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);}
Below isGetAll
Method HTTP response:
HTTP/1.1 200 OKContent-Type: application/json; charset=utf-8Server: Microsoft-IIS/10.0Date: Thu, 18 Jun 2015 20:51:10 GMTContent-Length: 82[{"Key":"4f67d7c5-a2a9-4aae-b030-16003dd829ae","Name":"Item1","IsComplete":false}]
In the subsequent tutorials, I will show you how to use the Fiddler tool to view HTTP responses.
Routing and URL path
The [HttpGet] feature indicates that these methods Support http get and mark the url path for methods in the controller by performing the following steps:
- Label the template in the controller feature:
[Route("api/[controller]")]
;
- Replace
[Controller]
Is the actual controller name (As before, the Convention is better than the configuration. All controllers must useController
The end of the template can be omitted.Controller
Suffix, Translator's note). For exampleTodoController
{controller}
Changetodo
You can. ASP. net mvc Core is case-insensitive.
- If
[HttpGet]
There is also a template that can be appended to the path. In this example, the template string is not used.
ForGetById
Method, in the actual HTTP Request{id}
Is a placeholder, used when the client is runningtodo
When MVC callsGetById
The{id}
The placeholder is assigned to the Url Methodid
Parameter.
Change the startup Url of "api/todo"
- Right-click the project> Properties
- SelectDebugTabLaunch URLTo
api/todo
:
For more information about Request Routing, see routing to Controller Action.
Return Value
GetAll
Method to return the CLR object. MVC automatically serializes the object to JSON and writes the JSON object to the response message body. The response status code is 200. If no exception is handled. (Unprocessed exceptions are generally converted to 5xx errors .)
On the contrary,GetById
Will returnIActionResult
Type, which represents a more general result object. BecauseGetById
There are two different return values:
- If no data item can match the ID, the method returns the 404 error and ends with the return of NotFound.
- Otherwise, the method returns 200 and the JSON response body. And finally end with the returned ObjectResult.
Use Fiddler to call APIs
This step is optional, but it helps us to view the original HTTP response returned by the Web API.
In Visual Studio, click^F5
Start the project. Visual Studio starts the browser and navigatehttp://localhost:port/api/todo
,PortIs a random number. If you use Chrome, Edge, or Firefox,TodoThe data is displayed. If you use IE, a window will pop up prompting you to open or saveTodo. jsonFile.
Start Fiddler, fromFileMenu, deselectCapture Traffic. This will disable HTTP traffic capture.
SelectComposerPage. InParsedTab, enterhttp://localhost:port/api/todo
,PortIs the actual port number. ClickExecuteSend a request.
The result is displayed in the sessions list. The response code is 200. UseInspectorsOption card to view the response content, including the Request body.
Implement other CRUD operations
The last step is to addCreate
,Update
AndDelete
These three methods. These methods are centered around a topic, so I will only list the code and mark the major differences.
Create
[HttpPost]public IActionResult Create([FromBody] TodoItem item){ if (item == null) { return BadRequest(); } TodoItems.Add(item); return CreatedAtRoute("GetTodo", new { controller = "Todo", id = item.Key }, item);}
This is an http post method, which is declared using the [HttpPost] feature. The [FromBody] feature tells MVC to obtain the value of the to-do item from the body of the HTTP request.
When a client sends a POST request to the server to create a resource, the CreatedAtRoute method returns the standard 201 response.CreateAtRoute
The Location header is added to the response. The Location header specifies the URI of the newly created todo item. View 10.2.2 201 Created.
We use Fiddler to create and send a request:
This is a simple HTTP session. UseRawTab to view session data.
Request:
POST http://localhost:29359/api/todo HTTP/1.1User-Agent: FiddlerHost: localhost:29359Content-Type: application/jsonContent-Length: 33{"Name":"Alphabetize paperclips"}
Response:
HTTP/1.1 201 CreatedContent-Type: application/json; charset=utf-8Location: http://localhost:29359/api/Todo/8fa2154d-f862-41f8-a5e5-a9a3faba0233Server: Microsoft-IIS/10.0Date: Thu, 18 Jun 2015 20:51:55 GMTContent-Length: 97{"Key":"8fa2154d-f862-41f8-a5e5-a9a3faba0233","Name":"Alphabetize paperclips","IsComplete":false}
Update
[HttpPut("{id}")]public IActionResult Update(string id, [FromBody] TodoItem item){ if (item == null || item.Key != id) { return BadRequest(); } var todo = TodoItems.Find(id); if (todo == null) { return NotFound(); } TodoItems.Update(item); return new NoContentResult();}
Update
SimilarCreate
But http put is used. The response is 204 (No Content ). According to the HTTP specification, the PUT request requires the client to send the whole object update, not just the increment. To support partial update, use http patch.
Delete
[HttpDelete("{id}")]public void Delete(string id){ TodoItems.Remove(id);}
Method returns the 204 (NO content) response. This means that the client will receive a 204 response even if the project has been deleted or does not exist. There are two ways to deal with the problem of requesting to delete nonexistent resources:
- "Delete" indicates "deleting an existing item". If not, 404 is returned.
- "Delete" indicates "make sure this item is not in the Collection". If the project is not in the collection, 204 is returned.
Either method is reasonable. If a 404 error is received, the client must handle this situation.
Next step
- For more information about how to create backend services for native mobile apps, see create backend services for native mobile apps.