项目5 - Web API 接口开发
嗨,朋友!我是长安。
恭喜你来到最后一个项目!这次我们要开发一个完整的 Web API 应用,学习 ASP.NET Core Web API 的核心概念,实现 RESTful 风格的接口,为前端或移动端提供数据服务。这是从控制台应用到 Web 开发的重要跨越!
🎯 项目目标
通过这个项目,你将:
- 掌握 ASP.NET Core Web API 基础
- 学会设计和实现 RESTful API
- 理解 HTTP 协议和 REST 原则
- 学会使用依赖注入(DI)
- 掌握异步编程
- 学会 API 测试方法
- 理解前后端分离架构
📁 项目结构
TodoApi/
├── Controllers/
│ └── TodosController.cs
├── Models/
│ ├── TodoItem.cs
│ ├── CreateTodoDto.cs
│ └── UpdateTodoDto.cs
├── Services/
│ ├── ITodoService.cs
│ └── TodoService.cs
├── Program.cs
└── appsettings.json
🎯 项目需求
API 功能列表
我们将开发一个 任务管理 API (TodoAPI):
- GET /api/todos - 获取所有任务
- GET /api/todos/{id} - 获取单个任务
- POST /api/todos - 创建新任务
- PUT /api/todos/{id} - 更新任务
- DELETE /api/todos/{id} - 删除任务
- PATCH /api/todos/{id}/complete - 标记完成
- GET /api/todos/stats - 获取统计
技术栈
- ASP.NET Core 6.0+ - Web API 框架
- RESTful 设计 - REST 架构风格
- JSON - 数据格式
- 依赖注入 - DI 模式
- 异步编程 - async/await
- Swagger/OpenAPI - API 文档
项目创建
dotnet new webapi -n UserApi
cd UserApi
dotnet run
核心代码
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private static List<User> users = new List<User>
{
new User { Id = 1, Name = "张三", Email = "zhang@example.com" },
new User { Id = 2, Name = "李四", Email = "li@example.com" }
};
[HttpGet]
public ActionResult<IEnumerable<User>> GetAll()
{
return Ok(users);
}
[HttpGet("{id}")]
public ActionResult<User> GetById(int id)
{
var user = users.FirstOrDefault(u => u.Id == id);
if (user == null)
return NotFound();
return Ok(user);
}
[HttpPost]
public ActionResult<User> Create(User user)
{
user.Id = users.Max(u => u.Id) + 1;
users.Add(user);
return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);
}
[HttpPut("{id}")]
public ActionResult Update(int id, User user)
{
var existingUser = users.FirstOrDefault(u => u.Id == id);
if (existingUser == null)
return NotFound();
existingUser.Name = user.Name;
existingUser.Email = user.Email;
return NoContent();
}
[HttpDelete("{id}")]
public ActionResult Delete(int id)
{
var user = users.FirstOrDefault(u => u.Id == id);
if (user == null)
return NotFound();
users.Remove(user);
return NoContent();
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
🧪 测试 API
使用 Postman 或浏览器测试:
GET http://localhost:5000/api/users
GET http://localhost:5000/api/users/1
POST http://localhost:5000/api/users
PUT http://localhost:5000/api/users/1
DELETE http://localhost:5000/api/users/1
📚 知识点总结
| 知识点 | 说明 | 应用 |
|---|---|---|
| ASP.NET Core | Web 框架 | 整个项目 |
| RESTful API | REST 风格 | API 设计 |
| HTTP 动词 | GET/POST/PUT/DELETE | CRUD 操作 |
| 路由 | 属性路由 | [Route]、[HttpGet] |
| 模型绑定 | 参数绑定 | [FromBody]、DTO |
| 数据验证 | DataAnnotations | [Required] |
| 依赖注入 | DI 模式 | 服务注册 |
| 异步编程 | async/await | 异步方法 |
| Swagger | API 文档 | 文档生成 |
💡 优化建议
1. 添加异常处理
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
context.Response.StatusCode = 500;
await context.Response.WriteAsJsonAsync(new { error = ex.Message });
}
}
}
2. 添加 CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
app.UseCors("AllowAll");
🎯 练习任务
- 基础:完整实现上述代码
- 进阶:添加分页功能
- 挑战:添加搜索和筛选
- 超级:集成 Entity Framework Core
📝 项目小结
恭喜你完成了最后一个项目!通过这个项目,你:
- ✅ 掌握了 ASP.NET Core Web API 基础
- ✅ 学会了 RESTful API 设计
- ✅ 理解了 HTTP 协议和 REST 原则
- ✅ 掌握了依赖注入模式
- ✅ 学会了异步编程
- ✅ 掌握了 API 测试方法
🎉 所有项目完成!
恭喜你完成了所有 5 个实战项目!你现在已经具备:
- ✅ 控制台应用开发能力
- ✅ 面向对象设计能力
- ✅ 数据管理和持久化
- ✅ 文件系统操作能力
- ✅ Web API 开发能力
- ✅ 完整的项目开发经验
项目回顾
- 控制台计算器 - 掌握基础语法
- 待办事项管理 - 面向对象基础
- 学生管理系统 - CRUD 和 LINQ
- 文件管理器 - 文件系统操作
- Web API - Web 开发基础
💪 自我检测
- [ ] 能够创建 ASP.NET Core Web API 项目
- [ ] 理解 RESTful API 设计原则
- [ ] 会使用依赖注入
- [ ] 掌握异步编程
- [ ] 能够测试 API 端点
- [ ] 理解 HTTP 状态码
🚀 下一步建议
完成这 5 个项目后,你可以:
1. 深入学习数据库
- Entity Framework Core
- SQL Server / MySQL
- 数据库设计和优化
2. 学习前端技术
- HTML、CSS、JavaScript
- Vue.js 或 React
- 前后端集成
3. 学习微服务
- Docker 容器化
- 微服务架构
- gRPC 和消息队列
4. 做自己的项目
- 个人博客系统
- 在线商城平台
- 社交应用
5. 参与开源项目
- GitHub 上的 C# 项目
- 贡献代码和文档
- 提升实战技能
💪 给自己一个大大的赞!
从零基础到完成5个项目,你太棒了!编程之路才刚刚开始,继续保持热情和好奇心,你一定会成为优秀的开发者!
🎉 恭喜你完成 C# 完全学习指南!🎉
基础教程(15章)✅
进阶内容(10章)✅
实战项目(5个)✅
你已经掌握了 C# 开发的核心技能!
继续加油,编程路上与你同行!💪
—— 长安
