ASP.NET Core Web API GET 请求全攻略|多场景 GET Endpoint 实战
作者:xiaoxin.gao · 2025-07-02 · 阅读时间:6分钟
1. 引言 在任何 API 项目中,GET 请求是最常用的操作之一。它不仅负责返回资源列表,还常用于获取单条资 […]
文章目录
1. 引言
在任何 API 项目中,GET 请求是最常用的操作之一。它不仅负责返回资源列表,还常用于获取单条资源详情、辅助搜索和统计计算。本文将以“宝可梦(Pokemon)”为例,演示如何在 ASP.NET Core 中结合 Repository 模式与 AutoMapper,快速搭建一套完备的 GET 接口体系,满足常见业务需求。
2. 前置条件与项目结构
- 技术栈:.NET 6+、C#、Entity Framework Core、AutoMapper
-
项目结构:
/Interfaces
IPokemonRepository.cs
/Repositories
PokemonRepository.cs
/DTOs
PokemonDto.cs
/Helpers
MappingProfiles.cs
/Controllers
PokemonController.cs
/Data
AppDbContext.cs - 已在
Program.cs
中添加 DbContext、AutoMapper 及仓储依赖注入。
3. 接口层设计(Interfaces)
在 Interfaces/IPokemonRepository.cs
中,定义 GET 相关方法:
public interface IPokemonRepository
{
IReadOnlyCollection <Pokemon > GetPokemons(); // 列表查询
Pokemon GetPokemon(int id); // 详情查询
Pokemon GetPokemon(string name); // 按名称查询
decimal GetPokemonRating(int id); // 评分统计
bool PokemonExists(int id); // 存在性检测
}
3.1 列表查询:GetPokemons
返回所有宝可梦,适用于首页或 Feed 场景。
3.2 详情查询:GetPokemon(int id)
根据 ID 返回单个宝可梦详情,对应产品详情页。
3.3 按名称查询:GetPokemon(string name)
支持按名称搜索,适合前端实现搜索或模糊匹配功能。
3.4 评分统计:GetPokemonRating(int id)
根据评论表计算平均评分,返回 decimal
。
3.5 存在性检测:PokemonExists(int id)
简单布尔检测,常用于提前判断资源是否存在。
4. 仓储层实现(Repositories)
在 Repositories/PokemonRepository.cs
中实现接口方法:
public class PokemonRepository : IPokemonRepository
{
private readonly AppDbContext _context;
public PokemonRepository(AppDbContext context) = > _context = context;
public IReadOnlyCollection < Pokemon > GetPokemons() = >
_context.Pokemons.OrderBy(p = > p.Id).ToList();
public Pokemon GetPokemon(int id) = >
_context.Pokemons.FirstOrDefault(p = > p.Id == id);
public Pokemon GetPokemon(string name) = >
_context.Pokemons.FirstOrDefault(p = > p.Name == name);
public decimal GetPokemonRating(int id)
{
var reviews = _context.Reviews.Where(r = > r.Pokemon.Id == id).ToList();
if (reviews.Count == 0) return 0m;
return reviews.Sum(r = > r.Rating) / (decimal)reviews.Count;
}
public bool PokemonExists(int id) = >
_context.Pokemons.Any(p = > p.Id == id);
}
5. DTO 设计与 AutoMapper 配置
- DTO:限制返回字段,避免泄露敏感信息;
- AutoMapper:简化模型到 DTO 的转换。
public class PokemonDto { … }
public class MappingProfiles : Profile { … }
6. 控制器层实现(Controllers)
在 Controllers/PokemonController.cs
中,注入仓储与映射器,并实现各个 GET Endpoint。
6.1 注入仓储与映射器
public class PokemonController : ControllerBase
{
private readonly IPokemonRepository _repo;
private readonly IMapper _mapper;
…
}
6.2 列表与详情 Endpoint
// GET api/pokemon
[HttpGet]
public ActionResult < IReadOnlyCollection < PokemonDto > > GetPokemons()
{
var pokemons = _repo.GetPokemons();
var dtos = _mapper.Map < IReadOnlyCollection < PokemonDto > > (pokemons);
return Ok(dtos);
}
// GET api/pokemon/{id}
[HttpGet("{id}")]
public ActionResult < PokemonDto > GetPokemon(int id)
{
if (!_repo.PokemonExists(id))
return NotFound($"Pokemon {id} 未找到。");
var pokemon = _repo.GetPokemon(id);
var dto = _mapper.Map < PokemonDto > (pokemon);
return Ok(dto);
}
6.3 名称查询与存在性校验
// GET api/pokemon/name/{name}
[HttpGet("name/{name}")]
public ActionResult < PokemonDto > GetPokemonByName(string name)
{
var pokemon = _repo.GetPokemon(name);
if (pokemon == null) return NotFound($"Name={name} 的 Pokemon 未找到。");
return Ok(_mapper.Map < PokemonDto > (pokemon));
}
// GET api/pokemon/exists/{id}
[HttpGet("exists/{id}")]
public ActionResult < bool > PokemonExists(int id)
{
return Ok(_repo.PokemonExists(id));
}
6.4 评分统计 Endpoint
// GET api/pokemon/rating/{id}
[HttpGet("rating/{id}")]
public ActionResult < decimal > GetPokemonRating(int id)
{
if (!_repo.PokemonExists(id))
return NotFound($"Pokemon {id} 未找到。");
var rating = _repo.GetPokemonRating(id);
return Ok(rating);
}
7. Swagger 测试示例
- 列表查询:
GET /api/pokemon
,应返回所有宝可梦 DTO 列表。 - 详情查询:
GET /api/pokemon/1
,若存在返回200 OK + DTO
,否则404 Not Found
。 - 名称查询:
GET /api/pokemon/name/Pikachu
,检查大小写敏感性。 - 存在性检测:
GET /api/pokemon/exists/1
,返回布尔值。 - 评分统计:
GET /api/pokemon/rating/1
,返回decimal
格式平均分,若无评论返回0.0
。
8. 小结与最佳实践
- 明确接口契约:在
Interfaces
层预先定义所有 GET 方法,提升可维护性。 - Repository 模式:将数据访问逻辑集中,控制器只关心业务流程。
- DTO + AutoMapper:确保返回结果精简、安全,并快速完成对象映射。
- 丰富 Endpoint:除基础列表与详情,还可覆盖搜索、统计、校验等常见场景。
- 参数校验:在 Controller 层预先判断资源存在性,避免后续 NullReference 异常。
通过以上步骤,你已掌握 ASP.NET Core Web API 中最全面的 GET 接口设计与实现方法。祝你快速构建高质量、易维护的后端服务!
热门推荐
一个账号试用1000+ API
助力AI无缝链接物理世界 · 无需多次注册
3000+提示词助力AI大模型
和专业工程师共享工作效率翻倍的秘密
热门API
- 1. AI文本生成
- 2. AI图片生成_文生图
- 3. AI图片生成_图生图
- 4. AI图像编辑
- 5. AI视频生成_文生视频
- 6. AI视频生成_图生视频
- 7. AI语音合成_文生语音
- 8. AI文本生成(中国)