Search code examples
c#asp.net

Cannot resolve action in CreatedAtAction(nameof(ActionName))


I have Api Controller and when create new object in database in Post method i want go to the other api action. But in case when method is specify called (GetByIdAsync) i got error Cannot resolve action GetByIdAsync. If action is called other name - everythink is ok.

Error code (additional screenshot First screenshot)

[ApiController]
[Route("items")]
public class ItemsController : ControllerBase
{
  private readonly ItemsRepository itemsRepository = new();

  [HttpGet("{id}")]
  public async Task<ActionResult<ItemDtos>> GetByIdAsync(Guid id)
  {
    var item = (await itemsRepository.GetAsync(id)).AsDto();

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

    return item;
  }

  [HttpPost]
  public async Task<ActionResult> CreateAsync(CreateItemDtos createItemDto)
  {
    var item = new Item {
    Name = createItemDto.Name, 
    Description = createItemDto.Description, 
    Price = createItemDto.Price,
    CreatedDate = DateTimeOffset.UtcNow
    };

    await itemsRepository.CreateAsync(item);

    //Cannot resolve action 'GetByIdAsync'
    return CreatedAtAction(nameof(GetByIdAsync), new {id = item.Id}, item);
  }
}

Working Code (additional screenshot Second screenshot)

[ApiController]
[Route("items")]
public class ItemsController : ControllerBase
{
  private readonly ItemsRepository itemsRepository = new();

  [HttpGet("{id}")]
  public async Task<ActionResult<ItemDtos>> GetByIdAsync2(Guid id)
  {
    var item = (await itemsRepository.GetAsync(id)).AsDto();

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

    return item;
  }

  [HttpPost]
  public async Task<ActionResult> CreateAsync(CreateItemDtos createItemDto)
  {
    var item = new Item {
    Name = createItemDto.Name, 
    Description = createItemDto.Description, 
    Price = createItemDto.Price,
    CreatedDate = DateTimeOffset.UtcNow
    };

    await itemsRepository.CreateAsync(item);

    return CreatedAtAction(nameof(GetByIdAsync2), new {id = item.Id}, item);
  }
}

Solution

  • I'm not 100% sure why it gives this error but a solution is to assign it to a local variable and use that.

      [HttpPost]
      public async Task<ActionResult> CreateAsync(CreateItemDtos createItemDto)
      {
        var item = new Item
        {
            Name = createItemDto.Name, 
            Description = createItemDto.Description, 
            Price = createItemDto.Price,
            CreatedDate = DateTimeOffset.UtcNow
        };
    
        await itemsRepository.CreateAsync(item);
    
        var actionName = nameof(GetByIdAsync2);
        return CreatedAtAction(actionName, new { id = item.Id }, item);
      }