返回ASP.NET Core 2.2中新建资源的URI

时间:2019-02-22 22:22:44

标签: c# asp.net-web-api asp.net-core

我想返回ASP.NET Core 2.2中新创建的资源的位置URI。这是为食品供应商获取食品的方法:

[HttpGet("{foodVendorId}/foodItems/{foodItemId}", Name = "GetFoodItem")]
public IActionResult GetFoodVendorFoodItem(int foodVendorId, int foodItemId)
{
    if (!_foodDeliveryAPIRepository.FoodVendorExists(foodVendorId))
    {
        return NotFound();
    }

    var foodItem = _foodDeliveryAPIRepository.GetFoodItemForFoodVendor(foodVendorId, foodItemId);

    if (foodItem == null)
    {
        return NotFound();
    }

    var foodItemResult = Mapper.Map<FoodItemDto>(foodItem);

    return Ok(foodItemResult);
}

以下是为食品供应商添加或创建食品的方法:

[HttpPost("{foodVendorId}/foodItems")]
public IActionResult CreateFoodItem(int foodVendorId, [FromBody] FoodItemForCreationDto foodItem)
{
    if (foodItem == null)
    {
        return BadRequest();
    }

    if (!_foodDeliveryAPIRepository.FoodVendorExists(foodVendorId))
    {
        return NotFound();
    }

    var finalFoodItem = Mapper.Map<Entities.FoodItem>(foodItem);

    _foodDeliveryAPIRepository.AddFoodItemForFoodVendor(foodVendorId, finalFoodItem);

    if (!_foodDeliveryAPIRepository.Save())
    {
        return StatusCode(500, "A problem happened while handling your request.");
    }

    var createdFoodItemToReturn = Mapper.Map<Models.FoodItemDto>(finalFoodItem);

    return CreatedAtRoute("GetFoodItem", new
        { foodVendorId = foodVendorId, id = createdFoodItemToReturn.Id }, createdFoodItemToReturn);
}

创建FoodItem后,值将进入数据库,但创建后返回500服务器错误。调试之后,我意识到错误出在CreatedAtRoute的return语句中-

return CreatedAtRoute("GetFoodItem", new
        { foodVendorId = foodVendorId, id = createdFoodItemToReturn.Id }, createdFoodItemToReturn);

我在做什么不对? -This不能解决我的问题。

1 个答案:

答案 0 :(得分:1)

我尝试重现您的例外情况,但我做到了。调试后,我注意到当您返回CreatedAtRoute时,您传递了 id 作为 foodItemId 的名称,这就是问题所在。

您的路线参数名称应该与GET操作输入的名称完全相同。

这是您用来测试的简化代码:

[HttpGet("{foodVendorId}/foodItems/{foodItemId}", Name = "GetFoodItem")]
public IActionResult GetFoodVendorFoodItem(int foodVendorId, int foodItemId)
{
    return Ok(";)");
}

[HttpPost("{foodVendorId}/foodItems")]
public IActionResult CreateFoodItem(int foodVendorId)
{
    return CreatedAtRoute("GetFoodItem", new { foodVendorId, /* this was the problem => */ foodItemId = 5 }, new { result = "Done" });
}