2

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);
  }
}
Adam Wróbel
  • 344
  • 6
  • 25
  • 2
    Does this answer your question? [When methods have the name ...Async the exception "System.InvalidOperationException: No route matches the supplied values" occurs](https://stackoverflow.com/questions/62202488/when-methods-have-the-name-async-the-exception-system-invalidoperationexcept) – madreflection Feb 14 '22 at 20:59

1 Answers1

4

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);
  }
nelsontruran
  • 514
  • 4
  • 18