簡體   English   中英

無法解析 CreatedAtAction(nameof(ActionName)) 中的操作

[英]Cannot resolve action in CreatedAtAction(nameof(ActionName))

我有 Api 控制器,當在 Post 方法中的數據庫中創建新對象時,我想轉到其他 api 操作。 但是,如果指定調用方法 (GetByIdAsync) 我得到錯誤Cannot resolve action GetByIdAsync 如果動作被稱為其他名稱-everythink 都可以。

錯誤代碼(附加截圖第一張截圖

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

工作代碼(附加截圖第二個截圖

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

我不是 100% 確定它為什么會出現此錯誤,但解決方案是將其分配給局部變量並使用它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM