【发布时间】: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);
}
}
【问题讨论】: