Error sending a route to the same api/Controller/Action in a Webapi

Asked

Viewed 86 times

1

I’m having the following error, I perform the following operation:

        // POST: api/Funcionario/AddFuncionario
    [HttpPost("AddFuncionario")]
    public IActionResult AddFuncionario([FromBody] Funcionario Func)
    {
        if(Func == null)
        {
            return BadRequest();
        }

        funcionarioRepository.AddFuncionario(Func);
        return CreatedAtRoute("BuscarPorId/{id}", new { id = Func.Id }, Func);

    }

only that, on my return Createdatroute, the action Buscarporid is not being found, the following error appears: Invalidoperationexception: No route Matches the supplied values.

Follow my Api Action:

        [HttpGet("BuscarPorId/{id}")]
    public IActionResult BuscarPorId(int id)
    {
        var item = funcionarioRepository.BuscarPorFuncionario(id);
        return new ObjectResult(item);
    }
  • Okay, I did the following, named my request: [Httpget("Buscarporid/{id}", Name = "Buscarporid")] and in Return createdAtroute it looks like this: Return Createdatroute("Buscarporid", new { id = Func.Id }, Func);

1 answer

0

You need to name the route, the CreatedAtRoute search for a route by name and not by "template" hers.

[HttpGet("BuscarPorId/{id}", Name = "NomeDaRota")]
public IActionResult BuscarPorId(int id) { }

public IActionResult AddFuncionario([FromBody] Funcionario Func)
{
    // (...)
    return CreatedAtRoute("NomeDaRota", new { id = Func.Id }, Func);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.