2. 前置條件與項目結構


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 配置

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. 小結與最佳實踐

通過以上步驟,你已掌握 ASP.NET Core Web API 中最全面的 GET 接口設計與實現方法。祝你快速構建高質量、易維護的后端服務!

上一篇:

ASP.NET Core JWT 生成實戰|Claims 與 Roles 深度解析

下一篇:

ASP.NET Core Web API GET 請求進階|Category 與 Country 控制器實戰
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費