我是靠谱客的博主 受伤绿草,这篇文章主要介绍使用 ASP.NET Core 创建 Web API,现在分享给大家,希望可以做个参考。

这是一篇图文基础教程:适合新手练习。

开发环境VS2019+.net core 3.0

需要安装core 3.0

检验是否安装core 3.0  ----cmd   命令dotnet --info

运行vs2019

创建新项目---选择ASP.NET Core Web应用程序

配置项目

选择项目类型--API

点击创建---等一会就会有模版了

运行这个项目,会在浏览器上显示一个json数据。这个默认生成的数据。

然后下一步:

创建Models文件夹:

然后右键Models文件夹,添加一个类文件:TodoItem

复制代码
1
2
3
4
5
6
7
8
9
10
namespace WebTest.Models { public class TodoItem { public int Id { get; set; } public string Name { get; set; } public bool IsBlack { get; set; } } }

下一步需要引用nuget扩展包

连续步骤 添加:Microsoft.EntityFrameworkCore.SqlServer

和        Microsoft.EntityFrameworkCore.InMemory

安装完之后,右键Models文件夹添加TodoContext 数据库上下文类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
using Microsoft.EntityFrameworkCore; namespace WebTest.Models { public class TodoContext : DbContext { public TodoContext(DbContextOptions<TodoContext> options) : base(options) { } public DbSet<TodoItem> TodoItems { get; set; } } }

上下文添加完之后需要Startup.cs修改一下:向依赖关系注入 (DI) 容器进行注册

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.EntityFrameworkCore; using WebTest.Models; namespace WebTest { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList")); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }

下一步,添加控制器:右键Controllers文件夹,

继续:

继续:选择对应的项:

控制器代码:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using WebTest.Models; namespace WebTest.Controllers { [Route("api/[controller]")] [ApiController] public class TodoItemsController : ControllerBase { private readonly TodoContext _context; public TodoItemsController(TodoContext context) { _context = context; } // GET: api/TodoItems [HttpGet] public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems() { return await _context.TodoItems.ToListAsync(); } // GET: api/TodoItems/5 [HttpGet("{id}")] public async Task<ActionResult<TodoItem>> GetTodoItem(int id) { var todoItem = await _context.TodoItems.FindAsync(id); if (todoItem == null) { return NotFound(); } return todoItem; } // PUT: api/TodoItems/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPut("{id}")] public async Task<IActionResult> PutTodoItem(int id, TodoItem todoItem) { if (id != todoItem.Id) { return BadRequest(); } _context.Entry(todoItem).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TodoItemExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } // POST: api/TodoItems // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see https://aka.ms/RazorPagesCRUD. [HttpPost] public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem) { _context.TodoItems.Add(todoItem); await _context.SaveChangesAsync(); //return CreatedAtAction("GetTodoItem", new { id = todoItem.Id }, todoItem); //nameof是为了调用方法时不采用硬编码 return CreatedAtAction(nameof(GetTodoItem), new { id = todoItem.Id }, todoItem); } // DELETE: api/TodoItems/5 [HttpDelete("{id}")] public async Task<ActionResult<TodoItem>> DeleteTodoItem(int id) { var todoItem = await _context.TodoItems.FindAsync(id); if (todoItem == null) { return NotFound(); } _context.TodoItems.Remove(todoItem); await _context.SaveChangesAsync(); return todoItem; } private bool TodoItemExists(int id) { return _context.TodoItems.Any(e => e.Id == id); } } }

这样之后,就可以使用Postman来测试:

浏览器运行可以看到结果。使用postman的时候,程序需要运行着。

可参考:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.0&tabs=visual-studio

最后

以上就是受伤绿草最近收集整理的关于使用 ASP.NET Core 创建 Web API的全部内容,更多相关使用内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(63)

评论列表共有 0 条评论

立即
投稿
返回
顶部