【问题标题】:Cannot resolve action in CreatedAtAction(nameof(ActionName))无法解析 CreatedAtAction(nameof(ActionName)) 中的操作
【发布时间】:2022-07-01 06:48:15
【问题描述】:

我有 Api 控制器,当在 Post 方法中的数据库中创建新对象时,我想转到其他 api 操作。但是,如果指定调用方法(GetByIdAsync),我会收到错误Cannot resolve action GetByIdAsync。如果行动被称为其他名称 - 一切都可以。

错误代码(附加截图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);
  }
}

工作代码(附加截图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);
  }
}

【问题讨论】:

标签: c# asp.net


【解决方案1】:

我不是 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);
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多