传递给 MVC 控制器的 id 总是映射为 0

id passed to MVC controller always mapped as 0

我有一个充满车辆数据的数据库。我的 API 可用于 return 所有车辆的列表,但不能用于单个车辆。下面列出了控制器代码以及来自 Startup.Configure

的 mvc 映射

为什么无论我使用什么参数(比如 id 为“27”)它总是映射为 0?

[HttpGet("{id:int}")]
public IActionResult GetVehicle(int vehicleId_)
{
    try{
        var specificVehicle = _vehicleRepository.GetVehicleById(vehicleId_);

        if (specificVehicle == null) return NotFound();
        return Ok(_mapper.Map<VehicleViewModel>(specificVehicle));
    }
    catch(Exception ex)
    {
        _logger.LogError($"Failed to retrieve specific vehicle : {ex}");
        return BadRequest("An Error Ocurred retrieving a specific vehicle. 
         Check Logs.");
     }
}

来自Startup.Configure

app.UseMvc( config =>{
config.MapRoute(
    name    : "Default",
    template: "{controller}/{action}/{id?}",
    defaults: new {controller = "Home", action = "Index"}
);

Why is it that whatever parameter I use (say '27' for the id) it is always mapped as 0?

路由模板中的参数名称需要与操作中的参数名称相匹配。

您目前在路线模板中的名称 {id:int} 与操作中的名称 int vehicleId_ 不同。

[HttpGet("{id:int}")]
public IActionResult GetVehicle(int id) {
    try{
        var specificVehicle = _vehicleRepository.GetVehicleById(id);

        if (specificVehicle == null) return NotFound();
        return Ok(_mapper.Map<VehicleViewModel>(specificVehicle));
    }
    catch(Exception ex)
    {
        _logger.LogError($"Failed to retrieve specific vehicle : {ex}");
        return BadRequest("An Error Ocurred retrieving a specific vehicle. 
         Check Logs.");
     }
}

引用Routing to controller actions in ASP.NET Core