ASP.NET Core Web API Route属性被忽略返回404错误如何解决?
问题根因分析
- 首先是Action路由前缀问题:你在Action上定义的
[Route("api/Interest/GetInterests")]没有以/或者~/开头,属于相对路由模板,会和控制器上的[Route("api/[controller]")]拼接,最终生成的实际路由是api/3/api/Interest/GetInterests,和你访问的地址完全不匹配。 - 其次是控制器命名不符合约定:ASP.NET Core路由的
[controller]令牌会自动替换为控制器类名去掉Controller后缀的部分,你的控制器类名为Controller3,所以替换后的值为3,和你预期的Interest完全不符。 - 额外存在逻辑bug:Delete方法中当
existingInterest为null时,仍然访问existingInterest.Id会直接抛出空引用异常。
修复方案
提供两种可选方案,推荐第二种符合路由约定的写法:
方案1:快速修复硬编码路由
给所有Action上的硬编码路由开头加/声明为绝对路由,跳过和控制器路由的拼接逻辑即可:
// 所有硬编码的Route属性统一加/前缀 [HttpGet] [Route("[action]")] [Route("/api/Interest/GetInterests")] public IEnumerable<Interest> GetEmployees() { return _interest.GetInterests(); }
修改完成后访问https://localhost:44316/api/Interest/GetInterests即可正常响应。
方案2:符合路由约定的规范写法(推荐)
删除所有Action上冗余的硬编码路由,修改控制器命名符合约定即可:
- 重命名控制器类,适配
[controller]令牌的替换规则:
[ApiController] [Route("api/[controller]")] // 把Controller3改为InterestController,[controller]会自动替换为Interest public class InterestController : ControllerBase { private readonly IServiceContract3 _interest; public InterestController(IServiceContract3 interest) { _interest = interest; } [HttpGet] [Route("[action]")] // 自动生成路由:api/Interest/GetEmployees public IEnumerable<Interest> GetEmployees() { return _interest.GetInterests(); } // 其余Action无需修改,会自动生成对应路由: // api/Interest/AddInterest、api/Interest/UpdateInterest等 }
- 可以将
GetEmployees方法名改为GetInterests,和业务语义保持一致,访问地址就和你原来使用的https://localhost:44316/api/Interest/GetInterests完全匹配。
额外逻辑修复
同步修正Delete方法的空引用问题:
[HttpDelete] [Route("[action]")] public IActionResult DeleteInterest(int id) { var existingInterest = _interest.GetInterest(id); if (existingInterest != null) { _interest.DeleteInterest(existingInterest.Id); return Ok(); } // 直接使用传入的id,避免访问null对象的属性 return NotFound($"Interest Not Found with ID : {id}"); }
内容的提问来源于stack exchange,提问作者ItzSebas
相关产品推荐
相关产品推荐

