
深入解析API网关策略:认证、授权、安全、流量处理与可观测性
在前一节视频中,我们已完成评论的创建与关联逻辑;由于评论已与文章等实体形成“一对多”关系,更新评论时无需额外处理关联,只需依据评论的ID定位并覆盖字段即可。
本文将带你一步步实现从 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