
深入解析API網關策略:認證、授權、安全、流量處理與可觀測性
本文將帶你一步步實現從 Controller、DTO、Repository 到映射及測試的全流程更新功能。
在 CommentController
中添加如下方法簽名:
[HttpPut("{id:int}")]
public async Task < IActionResult > UpdateCommentAsync(
[FromRoute] int id,
[FromBody] UpdateCommentRequestDto dto)
{
// 后續補充更新邏輯
}
使用 [FromRoute]
明確綁定 URL 中的 id
,并用 [FromBody]
接收更新內容。
雖然更新 DTO 與創建 DTO 相似,但為保持清晰和靈活,仍建議單獨定義。
新建 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; }
}
在 ICommentRepository
接口中聲明:
Task < Comment? > UpdateAsync(int id, Comment comment);
在 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;
}
SaveChangesAsync()
即可持久化。在 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);
}
dotnet watch run
并打開 Swagger。在 PUT /api/comment/{id} 上點擊 Try it out:
id=4
,將 Title
修改為 “Apple is the best stock”,Content
同步更新。通過本篇實戰,相信你已掌握在 ASP.NET Core 中快速構建并測試評論更新接口的關鍵技巧,助力更健壯的后端服務開發!
原文引自YouTube視頻:https://www.youtube.com/watch?v=wpBTiISt6UE