Search code examples
c#asp.net-core.net-coreasp.net-core-mvcasp.net-core-routing

id passed to MVC controller always mapped as 0


I have a database full of vehicle data. My API can be used to return a list of all vehicles, but not a single vehicle. The controller code is listed below along with my mvc mapping from Startup.Configure

Why is it that whatever parameter I use (say '27' for the id) it is always mapped as 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.");
     }
}

From Startup.Configure

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

Solution

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

    The name of the parameter in the route template needs to match the name of the parameter in the action.

    You currently have differing names {id:int} in the route template verses int vehicleId_ in the action.

    [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.");
         }
    }
    

    Reference Routing to controller actions in ASP.NET Core