ASP.NET Core Web API的HttpPut接口返回404问题排查
问题排查结论
Put接口返回404的核心原因是路由不匹配:
- 你给Action标记的路由特性是
[HttpPut("{id}")],要求请求路径必须携带id路由片段(例如请求地址为PUT /api/notes/1),但你的方法签名中没有定义参数来接收这个路由段的id值,路由系统无法将请求映射到该Action,请求在进入方法逻辑前就被框架返回404,和请求体配置无关。 - 现有代码还存在2个会引发运行异常的逻辑问题:
- 手动用
using包裹依赖注入生成的_datacontext,DbContext生命周期由DI容器统一管理,手动释放会导致同Controller其他接口访问DbContext时抛出对象已释放异常 - 未校验路由传入的id和请求体中Note的id是否一致,存在更新目标和请求数据不匹配的风险
- 手动用
正确的HttpPut实现
[HttpPut("{id}")] public IActionResult Put(int id, [FromBody] Note requestParam) { if (!ModelState.IsValid) { return BadRequest("Not a valid model"); } // 校验路径id与请求体id一致性 if (id != requestParam.Id) { return BadRequest("The id in the route does not match the id of the note in the request body"); } var existingNote = _datacontext.Note.FirstOrDefault(n => n.Id == id); if (existingNote == null) { return NotFound(); } existingNote.Title = requestParam.Title; existingNote.Description = requestParam.Description; existingNote.Completed = requestParam.Completed; _datacontext.SaveChanges(); return Ok(); }
调用注意事项
- 在SwaggerUI调试时,必须在接口参数面板的
id输入框填入要更新的笔记整数id,Swagger会自动将该id拼接到请求URL中,不能仅填写请求体内容 - 若使用.NET 6+版本并启用了可空引用类型,建议给Note实体的字符串属性标记可空,避免不必要的模型校验失败:
public class Note { [Key] public int Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public bool Completed { get; set; } }
- 你提供的DataContext配置、实体主键配置没有问题,不需要修改。
附原报错截图:
内容的提问来源于stack exchange,提问作者Jesus Castañeda
相关产品推荐
相关产品推荐

