当前位置:网站首页>Using asp Net core creating web API series
Using asp Net core creating web API series
2022-06-30 15:40:00 【zhoubangbang1】
Use ASP.NET Core establish Web API
This time mainly introduces the use of ASP.NET Core structure Web API Basic knowledge of .
In this tutorial , You will understand :
- establish Web API project .
- Add model classes and database context .
- Use CRUD Method to build the controller .
- Configure the routing 、URL Path and return value .
- Use Postman call Web API.
summary This tutorial will create the following API:
API | explain | Request body | Response Content |
GET /api/TodoItems | Get all the to-do items | nothing | An array of to-do items |
GET /api/TodoItems/{id} | Press ID To obtain a | nothing | To do list |
POST /api/TodoItems | Add a new item | To do list | To do list |
PUT /api/TodoItems/{id} | Update existing items | To do list | nothing |
DELETE /api/TodoItems/{id} | Delete the item | nothing | nothing |
establish Web project
from “ file ” From the menu “ newly build ”>“ project ” .
choice “ASP.NET Core Web Applications ” Templates , Click again “ next step ” .
Name the project TodoApi, And then click “ establish ” .
stay “ Create a new ASP.NET Core Web Applications ” In the dialog box , Confirm selection “.NET Core” and “ASP.NET Core 3.1” . choice “API” Templates , And then click “ establish ” .

Add model class
Model Is a group of classes that represent application management data . The model for this application is a single TodoItem class .
- stay “ Solution explorer ” in , Right click on the item . choice “ add to ” > “ New folder ” . Name the folder “Models” .
- Right click “Models” Folder , And then choose “ add to ” > “ class ” . Name the class TodoItem, And then choose “ add to ” .
- Replace the template code with the following code :
Build controller
- Right click Controllers Folder .
- choice “ add to ”>“ New build item ” .
- choice “ Its operation uses Entity Framework API controller ”, And then choose “ add to ”
Check PostTodoItem create Method
Replace PostTodoItem The return statement in , To use the nameof Operator :
[Route("api/posttodoitem")]
[ApiController]
public class PostTodoItemController : ControllerBase
{
public static List<TodoItem> todoItems = new List<TodoItem>() {
new TodoItem{Id=1,IsComplete=true,Name=" Zhang Yi Xing " },
new TodoItem{Id=2,IsComplete=true,Name=" Zheng Kai " },
new TodoItem{Id=3,IsComplete=true,Name=" Angela Baby " },
new TodoItem{Id=4,IsComplete=true,Name=" Chen He " },
new TodoItem{Id=5,IsComplete=true,Name=" Li Chen " },
};
[HttpPost]
public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
{
todoItems.Add(todoItem);
return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem);
// return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
}
[HttpGet]
public async Task<ActionResult<List<TodoItem>>> TodoItems()
{
return await Task.Run(() => todoItems);
// return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem);
}
[HttpGet("{id}")]
public async Task<ActionResult<TodoItem>>GetTodoItem(int id)
{
var todoItem = await Task.Run(() => todoItems.Where(x => x.Id == id)); ;
if (todoItem == null)
{
return NotFound();
}
return todoItem.FirstOrDefault();
}
}install Postman
This tutorial USES Postman test Web API.
- install Postman
- start-up Web application \( At testing time , It can be found in the project folder , function cmd
- Input :dotnet watch run )
For example, the project location is :

open Cmd

- start-up Postman.
- Ban SSL Certificate validation
- stay “ file ”>“ Set up ”(“ routine ” tab ) in , Ban “SSL Certificate validation ”
adopt Postman test PostTodoItem
- Create a new request .
- take HTTP Method set to
POST. - choice “ Text ” tab .
- choice “ original ” Radio button .
- Set type to JSON (application/json)
- In the body of the request , Enter the to-do list JSON:
{
Id:5
"name":"walk dog",
"isComplete":true
}
choice Send.

Test location header URI
- stay Headers Select... In the pane Response tab .
- Copy Location Header value :

- Set the method to “GET”.
- Paste URI( for example ,http://localhost:52655/api/posttodoitem/6).
- choice Send.

边栏推荐
- 1030 travel plan (30 points)
- Web technology sharing | whiteboard toolbar encapsulation of Web
- C language foundation - pointer array - initialization method & constant pointer array, pointer constant array
- Policy Center > Malware > Malware
- Policy Center > Misrepresentation
- The principle of fluent 2 rendering and how to realize video rendering
- Policy Center > Google Play‘s Target API Level Policy
- 1058 a+b in Hogwarts (20 points)
- Flask Sqlalchemy - automatically export the table model (flask sqlacodegen) & no single primary key problem ---orm (8)
- 1149 dangerous goods packaging (25 points)
猜你喜欢

topic: Privacy, Deception and Device Abuse

4.4 string

Message queue ten questions

Summary of gradient descent optimizer (rmsprop, momentum, Adam)

《你的灯亮着吗》开始解决问题前,得先知道“真问题”是什么

Rte2021 review HDR technology product practice and exploration

Complement (Niuke)

Start your global dynamic acceleration journey of Web services in three steps

终于看懂科学了!200张图领略人类智慧的巅峰

Industry analysis | the future of real-time audio and video
随机推荐
【时序数据库InfluxDB】Windows环境下配置InfluxDB+数据可视化,以及使用 C#进行简单操作的代码实例
Talk about why I started technical writing
[matlab] 3D drawing summary
How does sd-rtn ensure the high availability of RTE services after infrastructure failure
Jupyter notebook basic knowledge learning
Kubernetes: a comprehensive analysis of container choreography
001 basic knowledge (unfinished)
J - Borg maze (minimum spanning tree +bfs)
Policy Center > Malware > Malware
Developer practice - the future of Agora home AI audio and video
Four solutions to cross domain problems
【子矩阵数量统计】CF1181C Flag子矩阵数量统计
Experiment of the planning group of the West University of technology -- pipeline CPU and data processing Adventure
N - Is There A Second Way Left? (minimum spanning tree, Kruskal)
容器常用命令
The principle of fluent 2 rendering and how to realize video rendering
Technology sharing | anyrtc service single port design
1058 a+b in Hogwarts (20 points)
Google Play 索引表
RTC monthly tabloid programming challenge ended successfully in June; Review of the first anniversary of sound network's listing