API | Description | Request body | Body response |
GET / api / todo | Retrieve all to-do items | Not | To-do list array |
GET / api / todo / {id} | Get item by id | Not | To-do item |
POST / api / todo | Add new item | To-do item | To-do item |
PUT / api / todo / {id} | Update existing item | To-do item | Not |
PATCH / api / todo / {id} | Update existing item | To-do item | Not |
DELETE / api / todo / {id} | Delete item | Not | Not |
TodoApi
, uncheck Host in the cloud and click OK .TodoItem
class. Right-click on the Models directory and select Add> Class . TodoItem
class name TodoItem
and click Add . namespace TodoApi.Models { public class TodoItem { public string Key { get; set; } public string Name { get; set; } public bool IsComplete { get; set; } } }
ITodoRepository
. Use 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); } }
TodoRepository
class that implements the 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; } } }
TodoRepository
inside the controller, we will TodoRepository
using the built-in dependency injection support in ASP.NET Core.ITodoRepository
. In this case, the test is aimed at the logic of the controller, and not at the level of data access. using TodoApi.Models;
ConfigureServices
method, add the highlighted code: public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); services.AddSingleton<ITodoRepository, TodoRepository>(); }
TodoController
. 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; } } }
TodoController
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); }
GET /api/todo
GET /api/todo/{id}
GetAll
method will be as follows: 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}]
HttpGet
attribute ( HttpGetAttribute ) defines the HTTP GET method. The URL path for each method is constructed as follows:[Route("api/[controller]")]
[HttpGet]
attribute has a template string, add it to the path. In this example, the template string is not used.GetById
method: [HttpGet("{id}", Name = "GetTodo")] public IActionResult GetById(string id)
"{id}"
is a value that is replaced by the todo
element identifier. When GetById
is called, the value “{id}” in the URL is assigned to the id
parameter of the method.Name = "GetTodo"
creates a named route that allows it to be referenced in an HTTP response. This will be shown later in the example.GetAll
method returns an IEnumerable
. MVC automatically serializes the object to JSON and writes JSON to the response body. The response code for this method is 200, in the event that there are no unhandled exceptions (unhandled exceptions are translated to errors 5xx.)GetById
method returns a value of a more general type IActionResult
, which is represented by a large number of return types. GetById
has two different types of return values:NotFound
.ObjectResult
.http://localhost:port/api/values
opens, where port is an arbitrarily selected port number. If you are using Chrome, Edge or Firefox, the data will be displayed. When using IE, you will be prompted to open or save the values.json file.Create
, Update
and Delete
methods. This process is similar to what was discussed earlier, so the code will be shown here and the main differences highlighted. Create a project after adding or modifying the code. [HttpPost] public IActionResult Create([FromBody] TodoItem item) { if (item == null) { return BadRequest(); } TodoItems.Add(item); return CreatedAtRoute("GetTodo", new { id = item.Key }, item); }
CreateAtRoute
also adds a Location header to the response. The Location header indicates the URL of the created to-do item. Description: 10.2.2 201 Created .POST
as the HTTP method.{"Name":"<your to-do item>"}
.GetById
method that created the named route "GetTodo"
: [HttpGet("{id}", Name = "GetTodo")] public IActionResult GetById(string id)
[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
is similar to Create
, but uses HTTP PUT. Answer 204 (No content) . According to the HTTP specification, a PUT request requires the client to send the updated object completely, not just the delta. To support partial updates, use HTTP PATCH.Update
, but using HTTP PATCH. Answer 204 (No content) . [HttpPatch("{id}")] public IActionResult Update([FromBody] TodoItem item, string id) { if (item == null) { return BadRequest(); } var todo = TodoItems.Find(id); if (todo == null) { return NotFound(); } item.Key = todo.Key; TodoItems.Update(item); return new NoContentResult(); }
[HttpDelete("{id}")] public IActionResult Delete(string id) { var todo = TodoItems.Find(id); if (todo == null) { return NotFound(); } TodoItems.Remove(id); return new NoContentResult(); }
Source: https://habr.com/ru/post/312878/
All Articles