
一步步教你進行 Python REST API 身份驗證
技術棧:.NET Core 6+、C#、Entity Framework Core
項目結構(示例):
/Interfaces
IPokemonRepository.cs
ICategoryRepository.cs
/Repositories
PokemonRepository.cs
CategoryRepository.cs
/Controllers
PokemonController.cs
/DTOs
PokemonCreateDto.cs
/Mappings
MappingProfile.cs
已配置好數據庫上下文 AppDbContext
,包含 Pokemons
、Owners
、Categories
及對應的 Join 表 PokemonOwners
、PokemonCategories
。
在 Repository 模式中,接口定義了對外的方法約定。以 IPokemonRepository
為例:
public interface IPokemonRepository
{
bool CreatePokemon(int ownerId, int categoryId, Pokemon pokemon);
bool Save(); // 返回布爾值,指示保存成功與否
// … 其他方法如 Update、Delete、Get 等
}
要點:始終先定義接口,再在具體類中實現。接口扮演“藍圖”角色,有助于解耦與測試。
由于 Pokemon
與 Owner
、Category
之間是多對多關系,插入新 Pokemon
時,必須先從數據庫中獲取對應的 Owner
、Category
實體:
var owner = _context.Owners.FirstOrDefault(o => o.Id == ownerId);
var category = _context.Categories.FirstOrDefault(c => c.Id == categoryId);
接著,通過構造中間表實體,將它們與主實體關聯,并添加到相應的 DbSet:
var pokemonOwner = new PokemonOwner {
Owner = owner,
Pokemon = pokemon
};
var pokemonCategory = new PokemonCategory {
Category = category,
Pokemon = pokemon
};
_context.PokemonOwners.Add(pokemonOwner);
_context.PokemonCategories.Add(pokemonCategory);
注意:若直接使用 AutoMapper 映射,邏輯會較為隱晦,這里手動創建對象更清晰易懂。
最后,執行保存并返回結果:
public bool CreatePokemon(int ownerId, int categoryId, Pokemon pokemon)
{
// … 上述預加載與關聯構造
_context.Pokemons.Add(pokemon);
return Save();
}
public bool Save()
{
// 建議改為 >0 更嚴謹:return _context.SaveChanges() > 0;
return _context.SaveChanges() >= 0;
}
為了讓接口更加簡潔易讀,可將關聯實體的 Id(如 ownerId
、categoryId
)通過 URL Query 傳遞,而將主要數據通過 Body 傳輸:
[HttpPost]
public IActionResult CreatePokemon(
[FromQuery] int ownerId,
[FromQuery] int categoryId,
[FromBody] PokemonCreateDto dto)
{
var pokemon = _mapper.Map < Pokemon > (dto);
if (!_pokemonRepo.CreatePokemon(ownerId, categoryId, pokemon))
return BadRequest("創建失敗");
return NoContent(); // HTTP 204
}
定義精簡的 DTO,避免過度暴露數據庫結構:
public class PokemonCreateDto
{
public string Name { get; set; }
public string ImageUrl { get; set; }
// … 其他必要字段
}
在 MappingProfile
中添加映射規則:
CreateMap < PokemonCreateDto, Pokemon > ();
AutoMapper 會自動將 DTO 字段映射到實體,前提是名稱一致或已在 Profile 中自定義。
使用 Swagger UI 或 Postman 發起 POST 請求:
POST /api/pokemons?ownerId=1&categoryId=2
Body: { "name": "Mew", "imageUrl": "…" }
Pokemons
、PokemonOwners
、PokemonCategories
表,驗證數據是否正確插入。Save()
方法統一提交并返回布爾結果,提高可維護性。通過以上步驟,您已掌握在 .NET Core 中使用 Entity Framework Core 實現復雜 Create API 的核心方法,并能編寫出結構清晰、性能可控、易于維護的 RESTful 接口。
希望這篇教程能助您在 API 開發道路上走得更穩、更遠!
原文引自YouTube視頻:https://www.youtube.com/watch?v=j0-cnsCZf7g