本文將帶你一步步實現從 Controller、DTO、Repository 到映射及測試的全流程更新功能。


一、在 Controller 中定義 PUT 接口

  1. CommentController 中添加如下方法簽名:

    [HttpPut("{id:int}")]
    public async Task < IActionResult >  UpdateCommentAsync(
       [FromRoute] int id,
       [FromBody] UpdateCommentRequestDto dto)
    {
       // 后續補充更新邏輯
    }

  2. 使用 [FromRoute] 明確綁定 URL 中的 id,并用 [FromBody] 接收更新內容。

  3. 雖然更新 DTO 與創建 DTO 相似,但為保持清晰和靈活,仍建議單獨定義。


二、定義并使用 UpdateCommentRequestDto

  1. 新建 UpdateCommentRequestDto,與創建 DTO 同結構并可復用 DataAnnotations:

    public class UpdateCommentRequestDto
    {
       [Required, MinLength(5), MaxLength(280)]
       public string Title { get; set; }
    
       [Required, MinLength(5), MaxLength(280)]
       public string Content { get; set; }
    }
  2. 雖有重復屬性,但創建與更新場景中 DTO 往往需求不同,單獨維護更靈活。

三、在 Repository 實現 UpdateAsync 邏輯

  1. ICommentRepository 接口中聲明:

    Task < Comment? > UpdateAsync(int id, Comment comment);

  1. CommentRepository 中實現:

    public async Task < Comment? > UpdateAsync(int id, Comment comment)
    {
       var existing = await _context.Comments.FindAsync(id);
       if (existing == null) return null;
    
       // 僅更新允許修改的字段
       existing.Title   = comment.Title;
       existing.Content = comment.Content;
    
       await _context.SaveChangesAsync();
       return existing;
    }

  1. 通過 EF Core 的跟蹤機制,修改屬性后調用 SaveChangesAsync() 即可持久化。

四、DTO 轉實體的簡單映射

在 Controller 調用倉儲前,需將更新 DTO 轉為實體模型。可在 Controller 內部或借助擴展方法實現:

private static Comment ToComment(this UpdateCommentRequestDto dto) = >
    new() { Title = dto.Title, Content = dto.Content };

示例:

var updated = await _commentRepo.UpdateAsync(id, dto.ToComment());

映射后即調倉儲更新,并根據返回值判斷資源是否存在。


五、處理更新結果并返回響應

完整 Controller 代碼示例:

[HttpPut("{id:int}")]
public async Task<IActionResult> UpdateCommentAsync(
    [FromRoute] int id,
    [FromBody] UpdateCommentRequestDto dto)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var updated = await _commentRepo.UpdateAsync(id, dto.ToComment());
    if (updated == null)
        return NotFound($"Comment with ID {id} not found.");

    return Ok(updated);
}
  1. ModelState 校驗 DTO 完整性。
  2. 根據倉儲返回值判斷評論是否存在,返回 404200


六、Swagger UI 中測試更新功能

  1. 運行 dotnet watch run 并打開 Swagger。
  2. PUT /api/comment/{id} 上點擊 Try it out

  3. 在返回列表視圖或數據庫中查看,確保字段被正確修改。


小結與拓展

通過本篇實戰,相信你已掌握在 ASP.NET Core 中快速構建并測試評論更新接口的關鍵技巧,助力更健壯的后端服務開發!

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

上一篇:

ASP.NET Core 8 Web API EF Core 實踐指南(第3課)

下一篇:

ASP.NET Core 構建評論基礎設施:從接口到控制器完整實戰
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

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

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

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

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

#AI深度推理大模型API

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

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