xatja
xatja

Reputation: 11

CreatedAtRoute: System.InvalidOperationException: No route matches the supplied values

I don't really understand what is going on, and tried all sort of suggestions from other questions on Stack Overflow, such as using the ActionName attribute, passing SuppressAsyncSuffixInActionNames = false to AddControllers, using CreatedAtAction instead. The code seems pretty conventional for an ASP.NET Core REST API, so I don't really understand what is going on here, no matter what I do I get the No route matches the supplied values response, and the resource is added. Can it have something to do with .NET 6's insistence on explicitly declaring types as nullable?

[HttpGet("{id:guid}")]
[ActionName(nameof(GetProduct))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<ProductDto> GetProduct([FromQuery] Guid productId)
{
    var product = _productRepository.GetProductById(productId);

    return product is not null
        ? Ok(_mapper.Map<ProductDto>(product))
        : NotFound();
}

[HttpPost]
[Consumes(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<ProductDto> CreateProduct(
    [FromBody] ProductCreateDto product)
{
    var productEntity = _mapper.Map<Product>(product);

    _productRepository.CreateProduct(productEntity);

    var productDto = _mapper.Map<ProductDto>(productEntity);

    return CreatedAtRoute(
        nameof(GetProduct),
        new { productId = productDto.Id },
        productDto);
}

Upvotes: 0

Views: 384

Answers (1)

xatja
xatja

Reputation: 11

I'm a giddy goat. The solution was to change "{id:guid}" to "{productId:guid}":

[HttpGet("{productId:guid}", Name = nameof(GetProduct))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public ActionResult<ProductDto> GetProduct([FromRoute] Guid productId)
{
    var product = _productRepository.GetProductById(productId);

    return product is not null
        ? Ok(_mapper.Map<ProductDto>(product))
        : NotFound();
}

Thanks DiplomacyNotWar for rubber-ducking!

Upvotes: 1

Related Questions