所有文章 > API开发 > ASP.NET Core Web API GET 请求全攻略|多场景 GET Endpoint 实战
ASP.NET Core Web API GET 请求全攻略|多场景 GET Endpoint 实战

ASP.NET Core Web API GET 请求全攻略|多场景 GET Endpoint 实战

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 测试示例

  1. 列表查询GET /api/pokemon,应返回所有宝可梦 DTO 列表。
  2. 详情查询GET /api/pokemon/1,若存在返回 200 OK + DTO,否则 404 Not Found
  3. 名称查询GET /api/pokemon/name/Pikachu,检查大小写敏感性。
  4. 存在性检测GET /api/pokemon/exists/1,返回布尔值。
  5. 评分统计GET /api/pokemon/rating/1,返回 decimal 格式平均分,若无评论返回 0.0

8. 小结与最佳实践

  • 明确接口契约:在 Interfaces 层预先定义所有 GET 方法,提升可维护性。
  • Repository 模式:将数据访问逻辑集中,控制器只关心业务流程。
  • DTO + AutoMapper:确保返回结果精简、安全,并快速完成对象映射。
  • 丰富 Endpoint:除基础列表与详情,还可覆盖搜索、统计、校验等常见场景。
  • 参数校验:在 Controller 层预先判断资源存在性,避免后续 NullReference 异常。

通过以上步骤,你已掌握 ASP.NET Core Web API 中最全面的 GET 接口设计与实现方法。祝你快速构建高质量、易维护的后端服务!

#你可能也喜欢这些API文章!

我们有何不同?

API服务商零注册

多API并行试用

数据驱动选型,提升决策效率

查看全部API→
🔥

热门场景实测,选对API

#AI文本生成大模型API

对比大模型API的内容创意新颖性、情感共鸣力、商业转化潜力

25个渠道
一键对比试用API 限时免费

#AI深度推理大模型API

对比大模型API的逻辑推理准确性、分析深度、可视化建议合理性

10个渠道
一键对比试用API 限时免费