2. 環境與項目結構回顧


3. Owner GET 接口實現

3.1 接口層(IOwnerRepository)

定義三種方法,滿足關聯查詢與存在性校驗:

public interface IOwnerRepository
{
    IReadOnlyCollection < Pokemon > GetPokemonsByOwner(int ownerId); // 獲取某 Owner 的所有 Pokemon
    bool OwnerExists(int ownerId);                                // 判斷 Owner 是否存在
}

3.2 倉儲層(OwnerRepository)

Repositories/OwnerRepository.cs 中實現:

public class OwnerRepository : IOwnerRepository
{
    private readonly AppDbContext _context;
    public OwnerRepository(AppDbContext context) = > _context = context;

    public IReadOnlyCollection < Pokemon > GetPokemonsByOwner(int ownerId) = >
        _context.PokemonOwners
                .Where(po = > po.Owner.Id == ownerId)      // 過濾關聯表
                .Select(po = > po.Pokemon)                  // 投影到 Pokemon
                .ToList();

    public bool OwnerExists(int ownerId) = >
        _context.Owners.Any(o = > o.Id == ownerId);
}

3.3 DTO 與映射(OwnerDto)

3.4 控制器層(OwnerController)

[ApiController]
[Route("api/[controller]")]
public class OwnerController : ControllerBase
{
    private readonly IOwnerRepository _repo;
    private readonly IMapper _mapper;

    public OwnerController(IOwnerRepository repo, IMapper mapper)
    {
        _repo = repo;
        _mapper = mapper;
    }

    // GET api/owner/{id}/pokemons
    [HttpGet("{id}/pokemons")]
    public ActionResult < IReadOnlyCollection < PokemonDto >  >  GetPokemonsByOwner(int id)
    {
        if (!_repo.OwnerExists(id))
            return NotFound($"Owner {id} 未找到。");

        var pokemons = _repo.GetPokemonsByOwner(id);
        return Ok(_mapper.Map < IReadOnlyCollection < PokemonDto >  > (pokemons));
    }
}

4. Review GET 接口實現

4.1 接口層(IReviewRepository)

public interface IReviewRepository
{
    IReadOnlyCollection < Review >  GetReviews();                  // 全部 Review
    Review GetReview(int reviewId);                            // 單條 Review
    IReadOnlyCollection < Review > GetReviewsByPokemon(int pokemonId); // 某 Pokemon 的所有 Review
    bool ReviewExists(int reviewId);                           // Review 存在性校驗
}

4.2 倉儲層(ReviewRepository)

public class ReviewRepository : IReviewRepository
{
    private readonly AppDbContext _context;
    public ReviewRepository(AppDbContext context) = >  _context = context;

    public IReadOnlyCollection < Review > GetReviews() = >
        _context.Reviews.ToList();

    public Review GetReview(int reviewId) = >
        _context.Reviews.FirstOrDefault(r = > r.Id == reviewId);

    public IReadOnlyCollection < Review > GetReviewsByPokemon(int pokemonId) = >
        _context.Reviews
                .Where(r = > r.Pokemon.Id == pokemonId)
                .ToList();

    public bool ReviewExists(int reviewId) = >
        _context.Reviews.Any(r = > r.Id == reviewId);
}

4.3 DTO 與映射(ReviewDto)

4.4 控制器層(ReviewController)

[ApiController]
[Route("api/[controller]")]
public class ReviewController : ControllerBase
{
    private readonly IReviewRepository _repo;
    private readonly IMapper _mapper;

    public ReviewController(IReviewRepository repo, IMapper mapper)
    {
        _repo = repo;
        _mapper = mapper;
    }

    // GET api/review
    [HttpGet]
    public ActionResult < IReadOnlyCollection < ReviewDto > > GetReviews()
        = > Ok(_mapper.Map < IReadOnlyCollection < ReviewDto > >(_repo.GetReviews()));

    // GET api/review/{id}
    [HttpGet("{id}")]
    public ActionResult < ReviewDto > GetReview(int id)
    {
        if (!_repo.ReviewExists(id))
            return NotFound($"Review {id} 未找到。");
        return Ok(_mapper.Map < ReviewDto > (_repo.GetReview(id)));
    }

    // GET api/review/pokemon/{pokemonId}
    [HttpGet("pokemon/{pokemonId}")]
    public ActionResult < IReadOnlyCollection < ReviewDto > >  GetReviewsByPokemon(int pokemonId)
    {
        var reviews = _repo.GetReviewsByPokemon(pokemonId);
        return Ok(_mapper.Map < IReadOnlyCollection < ReviewDto > > (reviews));
    }
}

5. Reviewer GET 接口實現

5.1 接口層(IReviewerRepository)

public interface IReviewerRepository
{
    IReadOnlyCollection < Reviewer > GetReviewers();               // 全部 Reviewer
    Reviewer GetReviewer(int reviewerId);                       // 單條 Reviewer
    IReadOnlyCollection < Review > GetReviewsByReviewer(int reviewerId); // 某 Reviewer 的所有 Review
    bool ReviewerExists(int reviewerId);                        // Reviewer 存在性校驗
}

5.2 倉儲層(ReviewerRepository)

public class ReviewerRepository : IReviewerRepository
{
    private readonly AppDbContext _context;
    public ReviewerRepository(AppDbContext context) = > _context = context;

    public IReadOnlyCollection < Reviewer > GetReviewers() = >
        _context.Reviewers.Include(r = > r.Reviews).ToList();    // Include 加載導航屬性

    public Reviewer GetReviewer(int id) = >
        _context.Reviewers.FirstOrDefault(r = > r.Id == id);

    public IReadOnlyCollection < Review > GetReviewsByReviewer(int id) = >
        _context.Reviews.Where(r = > r.Reviewer.Id == id).ToList();

    public bool ReviewerExists(int id) = >
        _context.Reviewers.Any(r = > r.Id == id);
}

5.3 DTO 與映射(ReviewerDto)

5.4 控制器層(ReviewerController)

[ApiController]
[Route("api/[controller]")]
public class ReviewerController : ControllerBase
{
    private readonly IReviewerRepository _repo;
    private readonly IMapper _mapper;

    public ReviewerController(IReviewerRepository repo, IMapper mapper)
    {
        _repo = repo;
        _mapper = mapper;
    }

    // GET api/reviewer
    [HttpGet]
    public ActionResult < IReadOnlyCollection < ReviewerDto > >  GetReviewers()
        = > Ok(_mapper.Map < IReadOnlyCollection < ReviewerDto >  >(_repo.GetReviewers()));

    // GET api/reviewer/{id}
    [HttpGet("{id}")]
    public ActionResult < ReviewerDto > GetReviewer(int id)
    {
        if (!_repo.ReviewerExists(id))
            return NotFound($"Reviewer {id} 未找到。");
        return Ok(_mapper.Map < ReviewerDto > (_repo.GetReviewer(id)));
    }

    // GET api/reviewer/{id}/reviews
    [HttpGet("{id}/reviews")]
    public ActionResult < IReadOnlyCollection < ReviewDto > >  GetReviewsByReviewer(int id)
    {
        var reviews = _repo.GetReviewsByReviewer(id);
        return Ok(_mapper.Map < IReadOnlyCollection < ReviewDto > > (reviews));
    }
}

6. JSON 循環引用問題處理

對于多對多或雙向導航屬性,默認序列化會出現循環依賴。解決方法:在 Program.cs 中替換默認 JSON 序列化設置為 ReferenceHandler.IgnoreCycles

builder.Services.AddControllers()
    .AddJsonOptions(options = >
        options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles);

7. 小結與最佳實踐

通過本篇,你已完成 Owner、Review、Reviewer 三個模型的 GET 接口搭建,下一步將進入 POST/PUT/DELETE,實現完整的 CRUD 能力。期待與您下次再見!

原文引自YouTube視頻:https://www.youtube.com/watch?v=FEanWuYq7us

上一篇:

ASP.NET Core Web API GET 請求進階|Category 與 Country 控制器實戰

下一篇:

Flask、FastAPI 與 Django 框架比較:Python Web 應用開發教程
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

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

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

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

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

#AI深度推理大模型API

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

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