【问题标题】:id passed to MVC controller always mapped as 0传递给 MVC 控制器的 id 始终映射为 0
【发布时间】:2019-06-11 04:25:54
【问题描述】:

我有一个充满车辆数据的数据库。我的 API 可用于返回所有车辆的列表,但不能返回单个车辆。下面列出了控制器代码以及来自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"}
);

【问题讨论】:

  • 你能试试 [HttpGet)] public IActionResult GetVehicle(int vehicleId_)
  • 路由模板中的名称需要与参数名称匹配

标签: c# asp.net-core .net-core asp.net-core-mvc asp.net-core-routing


【解决方案1】:

为什么我使用的任何参数(比如 id 的“27”)总是映射为 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

【讨论】:

    猜你喜欢
    • 2019-02-04
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多