Samseen
Samseen

Reputation: 97

Returning the URI of a newly created resource in ASP.NET Core 2.2

I would like to return the location URI of a newly created resource in ASP.NET Core 2.2. Here is the method to get a Food Item for a Food Vendor:

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

And here is the method to add or create a food item for a Food Vendor:

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

Upon creating the FoodItem, the values gets to the database but it returns a 500 server error after creation. After debugging it, I realize the error is in the return statement of the CreatedAtRoute -

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

What am I not doing right? - This didn't solve my problem.

Upvotes: 1

Views: 4364

Answers (1)

Moien Tajik
Moien Tajik

Reputation: 2321

I've tried to reproduce your exception and I did. After debugging I noticed that when you return CreatedAtRoute you passed id as the name of foodItemId instead and that's the problem.

Your route parameter names should be exactly the same as your GET action input ones.

So here is your simplified code that I used to test:

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

Upvotes: 1

Related Questions