
FastAPI是什么?快速上手指南
在任何 API 项目中,GET 请求是最常用的操作之一。它不仅负责返回资源列表,还常用于获取单条资源详情、辅助搜索和统计计算。本文将以“宝可梦(Pokemon)”为例,演示如何在 ASP.NET Core 中结合 Repository 模式与 AutoMapper,快速搭建一套完备的 GET 接口体系,满足常见业务需求。
项目结构:
/Interfaces
IPokemonRepository.cs
/Repositories
PokemonRepository.cs
/DTOs
PokemonDto.cs
/Helpers
MappingProfiles.cs
/Controllers
PokemonController.cs
/Data
AppDbContext.cs
Program.cs
中添加 DbContext、AutoMapper 及仓储依赖注入。在 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); // 存在性检测
}
返回所有宝可梦,适用于首页或 Feed 场景。
根据 ID 返回单个宝可梦详情,对应产品详情页。
支持按名称搜索,适合前端实现搜索或模糊匹配功能。
根据评论表计算平均评分,返回 decimal
。
简单布尔检测,常用于提前判断资源是否存在。
在 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);
}
public class PokemonDto { … }
public class MappingProfiles : Profile { … }
在 Controllers/PokemonController.cs
中,注入仓储与映射器,并实现各个 GET Endpoint。
public class PokemonController : ControllerBase
{
private readonly IPokemonRepository _repo;
private readonly IMapper _mapper;
…
}
// 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);
}
// 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));
}
// 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);
}
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
。Interfaces
层预先定义所有 GET 方法,提升可维护性。通过以上步骤,你已掌握 ASP.NET Core Web API 中最全面的 GET 接口设计与实现方法。祝你快速构建高质量、易维护的后端服务!